Skip to main content
 首页 » 编程设计

c#之.NET 中的套接字未连接

2024年02月24日23三少

我无法连接一个简单的客户端和一个简单的服务器。当我运行服务器时,似乎没有任何问题,但是当我尝试通过客户端向它发送数据时,它抛出一个异常,说它没有在超时期限内连接。

这是我正在使用的服务器代码:

    public void server() 
    { 
        try 
        { 
            byte[] bytes = new byte[1024]; 
            int bytesReceived = 0; 
            String message = ""; 
            IPAddress direction = IPAddress.Parse(getIPExternal()); //getIPExternal return the public IP of the machine in which the programm runs 
            IPEndPoint directionPort = new IPEndPoint(direction, 5656); 
            Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
            socketServer.Bind(directionPort); 
            socketServer.Listen(100); 
            while (true) 
            { 
                Socket client = socketServer.Accept(); 
                bytesReceived = client.Receive(bytes); 
                message = System.Text.Encoding.Unicode.GetString(bytes, 0, bytesReceived); 
 
                editMultiline.Invoke(new writeMessageDelegate(writeMessage), new object[] { message, "client"}); //Ignore this, it is just to show the info in a textbox because the server code runs in a diferent thread 
 
                client.Shutdown(SocketShutdown.Both); 
                client.Close(); 
            } 
        } 
        catch (Exception ex) 
        { 
            MessageBox.Show(ex.Message, "Server error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
        } 
    } 

这样我就可以从运行程序的机器上获取公共(public) IP:

    public string getIPExternal() 
    { 
        string direction; 
        WebRequest request = WebRequest.Create("http://checkip.dyndns.org/"); 
        WebResponse response = request.GetResponse(); 
        StreamReader stream = new StreamReader(response.GetResponseStream()); 
        direction = stream.ReadToEnd(); 
        stream.Close(); 
        response.Close(); 
 
        //Search for the ip in the html 
        int first = direction.IndexOf("Address: ") + 9; 
        int last = direction.LastIndexOf("</body>"); 
        direction = direction.Substring(first, last - first); 
 
        return direction; 
    } 

这是我的客户端代码:

    public void client(string directionIP, string message) //directionIP is the IP from the computer to which i want to get connected 
    { 
        try 
        { 
            byte[] bytesSend = System.Text.Encoding.Unicode.GetBytes(message); 
            IPAddress direction = IPAddress.Parse(directionIP); 
            IPEndPoint directionPort = new IPEndPoint(direction, 5656); 
            Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
            socketClient.Connect(directionPort); 
            socketClient.Send(bytesSend); 
            socketClient.Close(); 
        } 
        catch (Exception ex) 
        { 
            MessageBox.Show(ex.Message, "Client error", MessageBoxButtons.OK, MessageBoxIcon.Error); 
        } 
    } 

任何建议都会很棒。

请您参考如下方法:

我建议查看 TcpListener 和 TcpClient 类,而不是摆弄套接字。Tcp* 类会为您做所有这些事情