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

标签 c# .net sockets

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

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

    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* 类会为您做所有这些事情

关于c# - .NET 中的套接字未连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2349925/

相关文章:

sockets - erlang 发送套接字西里尔字符数据

c# - 文件加密和解密导致解密时出现空白文件

c# - 使用 Odbc 连接 (System.Data.Odbc) 在 C# 中获取 MySql 表主键

C#,在函数中返回一个数组

java - 我通过套接字发送的 int 值与接收到的 int 值不同(Java)

.net - 带有取消 token 的 NetworkStream.ReadAsync 永远不会取消

C# 泛型 - 设计没有下限?

c# - 使用 Gmail 进行 ElMAH 错误记录?

c# - XmlReader ReadStartElement 导致 XmlException

c# - SQLConnection 中的无效参数