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

3

我正在尝试通过套接字连接从客户端向服务器发送数据。我已经成功地发送了第一组数据,但当我尝试发送第二组数据时,它从未发送,并且当我尝试发送第三组数据时它会给出一个 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();

1
由于在连接到您的服务器后,您会收到一个字符串,然后关闭连接。 - BugFinder
但是我们不是重新开放了吗? - Pareidolia
你的客户端没有显示任何形式的关闭...所以跟踪你的代码,它会向你展示问题出在哪里。 - BugFinder
1个回答

2

好的,这是一个愚蠢的错误。解决方法是我们应该接受一次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();
}

如果有关于套接字的文档,请评论一下。我想阅读它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接