.NET套接字突然停止工作

时间:2012-01-25 21:37:25

标签: c# network-programming asyncsocket

几个月前,我在当前的项目中编写了一个TCP Socket服务器和客户端,从那时起他们就一直在完美地工作。但到目前为止,我根本无法在两台机器之间建立连接,而这两台机器长时间没有连接通信。

设置非常简单:两台机器('A'和'B')通过以太网电缆直接连接(两者之间没有开关)。机器'A'也连接到我的家庭网络,允许互联网访问。机器'B'仅连接到'A'。我在'B'上运行TCP服务器,在'A'上运行客户端。

我在服务器端使用异步.NET Socket功能(BeginAccept等,在客户端使用BeginConnect等。调试好两端后,我只能确认服务器端似乎从未接到客户端的呼叫。我没有触及代码,它仍然适用于其他机器。

此外,两台机器之间没有其他通信问题。我正在使用Input Director共享一组键盘/鼠标,而正常的UNC路径可以很好地从另一台机器中浏览一台机器。

我测试了不同的端口,并且我已经将防火墙放在两边以便进行测量。我已经释放/更新了双方的连接,重新启动了两台机器以及我能想到的其他所有虚拟选项。

我承认我并不是非常精通网络,所以我非常感谢下一步要寻找的一些提示,因为我现在已经不知道接下来要检查什么了。 (我很确定这是一件非常愚蠢的事情,我只是忽略了。; O)


编辑(样本'尖峰'代码)

根据要求,我修改了Microsoft的示例套接字代码并对其进行了一些压缩(下图)。然后我测试了在机器'B'上运行服务器端和客户端端,它运行良好,但在机器'A'上运行同样的事情。客户端没有与服务器端联系。这是代码:

 public static class SocketServer
{
    private class StateObject
    {
        public Socket _workSocket;
        public const int BufferSize = 1024;
        public readonly byte[] _buffer = new byte[BufferSize];
        public readonly StringBuilder _sb = new StringBuilder();
    }

    private static readonly ManualResetEvent _s_allDone = new ManualResetEvent(false);

    public static void StartListening()
    {
        var ipHostInfo = Dns.Resolve(Dns.GetHostName());
        var ipAddress = ipHostInfo.AddressList[0];
        var localEndPoint = new IPEndPoint(ipAddress, 11000);
        var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(100);
            while (true)
            {
                _s_allDone.Reset();
                Console.WriteLine("Waiting for a connection...");
                listener.BeginAccept(acceptCallback, listener);
                _s_allDone.WaitOne();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        Console.WriteLine("\nPress ENTER to continue...");
        Console.Read();
    }

    private static void acceptCallback(IAsyncResult ar)
    {
        _s_allDone.Set();
        var listener = (Socket)ar.AsyncState;
        var handler = listener.EndAccept(ar);
        var state = new StateObject {_workSocket = handler};
        handler.BeginReceive(state._buffer, 0, StateObject.BufferSize, 0, readCallback, state);
    }

    private static void readCallback(IAsyncResult ar)
    {
        var state = (StateObject)ar.AsyncState;
        var handler = state._workSocket;
        int bytesRead = handler.EndReceive(ar);

        if (bytesRead <= 0) 
            return;

        state._sb.Append(Encoding.ASCII.GetString(state._buffer, 0, bytesRead));

        var content = state._sb.ToString();
        if (content.IndexOf("<EOF>") > -1)
        {
            Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
        }
        else
        {
            handler.BeginReceive(state._buffer, 0, StateObject.BufferSize, 0, readCallback, state);
        }
    }

    public static int Main(String[] args)
    {
        StartListening();
        return 0;
    }
}

public static class SocketClient
{
    private class StateObject
    {
        public Socket _workSocket;
        public const int BufferSize = 256;
        public readonly byte[] _receiveBuffer = new byte[BufferSize];
        public readonly StringBuilder _sb = new StringBuilder();
    }

    private const int RemotePort = 11000;
    private static readonly ManualResetEvent _s_connectDone = new ManualResetEvent(false);
    private static readonly ManualResetEvent _s_sendDone = new ManualResetEvent(false);
    private static readonly ManualResetEvent _s_receiveDone = new ManualResetEvent(false);

    // The response from the remote device.
    private static String _s_response = String.Empty;

    private static void startClient()
    {
        try
        {
            _s_connectDone.WaitOne(2000); // <-- gives server time to boot when on same machine
            var ipHostInfo = Dns.Resolve(Dns.GetHostName());
            var ipAddress = ipHostInfo.AddressList[0];
            var remoteEndPoint = new IPEndPoint(ipAddress, RemotePort);
            var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            client.BeginConnect(remoteEndPoint, connectCallback, client);
            _s_connectDone.WaitOne();
            send(client, "This is a test<EOF>");
            _s_sendDone.WaitOne();
            receive(client);
            _s_receiveDone.WaitOne();
            Console.WriteLine("Response received : {0}", _s_response);
            client.Shutdown(SocketShutdown.Both);
            client.Close();

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private static void connectCallback(IAsyncResult ar)
    {
        try
        {
            var client = (Socket)ar.AsyncState;
            client.EndConnect(ar);
            Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint);
            _s_connectDone.Set();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private static void receive(Socket client)
    {
        try
        {
            var state = new StateObject {_workSocket = client};
            client.BeginReceive(state._receiveBuffer, 0, StateObject.BufferSize, 0, receiveCallback, state);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private static void receiveCallback(IAsyncResult ar)
    {
        try
        {
            var state = (StateObject)ar.AsyncState;
            var client = state._workSocket;
            var bytesRead = client.EndReceive(ar);

            if (bytesRead > 0)
            {
                state._sb.Append(Encoding.ASCII.GetString(state._receiveBuffer, 0, bytesRead));
                client.BeginReceive(state._receiveBuffer, 0, StateObject.BufferSize, 0, receiveCallback, state);
            }
            else
            {
                if (state._sb.Length > 1)
                {
                    _s_response = state._sb.ToString();
                }
                _s_receiveDone.Set();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private static void send(Socket client, String data)
    {
        var byteData = Encoding.ASCII.GetBytes(data);
        client.BeginSend(byteData, 0, byteData.Length, 0, sendCallback, client);
    }

    private static void sendCallback(IAsyncResult ar)
    {
        try
        {
            var client = (Socket)ar.AsyncState;
            var bytesSent = client.EndSend(ar);
            Console.WriteLine("Sent {0} bytes to server.", bytesSent);
            _s_sendDone.Set();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    public static int Main()
    {
        startClient();
        return 0;
    }
}

0 个答案:

没有答案