服务器/客户端套接字连接

本文关键字:连接 套接字 客户端 服务器 | 更新日期: 2023-09-27 18:02:21

我正在尝试通过套接字连接从客户端发送数据到服务器。我成功发送了第一个数据,但当我试图发送第二个数据时,它永远不会发送,当我试图发送第三个数据时,它给了我Sockets.SocketException,我该如何解决这个问题?

服务器

byte[] buffer = new byte[1000];

        IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress ipAddress = iphostInfo.AddressList[0];
        IPEndPoint localEndpoint = new IPEndPoint(ipAddress, 8080);
        Socket sock = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

        sock.Bind(localEndpoint);
        sock.Listen(5);

        while (true) {
            Socket confd = sock.Accept();
            string data = null;
            int b = confd.Receive(buffer);
            data += Encoding.ASCII.GetString(buffer, 0, b);
            Console.WriteLine("" + data);
            confd.Close();
        }

byte[] data = new byte[10];
        IPHostEntry iphostInfo = Dns.GetHostEntry(Dns.GetHostName());
        IPAddress ipAdress = iphostInfo.AddressList[0];
        IPEndPoint ipEndpoint = new IPEndPoint(ipAdress, 8080);
        Socket client = new Socket(ipAdress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

        try {
            client.Connect(ipEndpoint);
            Console.WriteLine("Socket created to {0}", client.RemoteEndPoint.ToString());

            while (true) {
                string message = Console.ReadLine();
                byte [] sendmsg = Encoding.ASCII.GetBytes(message);
                int n = client.Send(sendmsg);
            }

        }
        catch (Exception e) {
            Console.WriteLine(e.ToString());
        }
        Console.WriteLine("Transmission end.");
        Console.ReadKey();

服务器/客户端套接字连接

好吧,真是个愚蠢的错误。这里是解决方案,我们应该接受一次socket。

while (true) {
    Socket confd = sock.Accept();
    string data = null;
    int b = confd.Receive(buffer);
    data += Encoding.ASCII.GetString(buffer, 0, b);
    Console.WriteLine("" + data);
    confd.Close();
}

更改为

Socket confd = sock.Accept();
while (true) {
    //Socket confd = sock.Accept();
    string data = null;
    int b = confd.Receive(buffer);
    data += Encoding.ASCII.GetString(buffer, 0, b);
    Console.WriteLine("" + data);
    //confd.Close();
}

如果有关于套接字的文档,请注释。