提问者:小点点

服务器和客户端之间的连续通信


我正在做一个作为服务器和客户端的程序。我要做的是让客户端显示一条消息,说明它是否连接到服务器。我认为最好的方法是让客户机每秒钟发送一条“活动”消息,然后让服务器响应。

在客户端向服务器发送一条消息的同时,服务器将显示它已连接一次,然后每次都显示它未连接。因此,我知道客户端正在工作,因为它报告未连接,但服务器只响应一次,然后停止。我的问题是服务器似乎只响应客户机一次。之后,我根本没有从服务器得到任何响应。

注意:到服务器的连接是在我检查连接之前调用的。我认为这与这个问题无关

客户端代码

public static void CheckServerConection(object Sender, EventArgs e)
    {
        try
        {
            NetworkStream nwStream = tcpClnt.GetStream();
            byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes("Alive");

            nwStream.Write(bytesToSend, 0, bytesToSend.Length);

            byte[] bytesToRead = new byte[tcpClnt.ReceiveBufferSize];
            int bytesRead = nwStream.Read(bytesToRead, 0, tcpClnt.ReceiveBufferSize);
            string received = Encoding.ASCII.GetString(bytesToRead, 0, bytesRead);

            if (received == "Alive")
            {
                ActiveConnection = true;
                Console.WriteLine("Connected");
            }
            else
            {
                ActiveConnection = false;
                Console.WriteLine("Not Connected");
            }
        }
        catch (Exception exception)
        {
            ActiveConnection = false;
            Console.WriteLine("Not Connected");
        } 
    }

服务器代码

public static void startServer()
    {
        try
        {
            IPAddress ipAd = IPAddress.Parse("0.0.0.0"); //Servers local IP address.
            int port = 36512;
            TcpListener listener = new TcpListener(ipAd, port);
            int i = 0;

            while (i == 0)
            {
                listener.Start();

                Console.WriteLine("Server has been started." + Environment.NewLine + "Running on: " + ipAd + ":" + port);
                Console.WriteLine("Waiting for client connection...");

                TcpClient client = listener.AcceptTcpClient();

                NetworkStream nwStream = client.GetStream();
                byte[] buffer = new byte[client.ReceiveBufferSize];

                int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

                string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                Console.WriteLine(dataReceived);

                nwStream.Write(buffer, 0, bytesRead);
                listener.Stop();
                client.Close();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }
    }

共1个答案

匿名用户

您正在循环外实例化侦听器。您将在循环中调用listener.stop()方法,这将关闭侦听器。之后,它就不能重启了。有关“示例”部分中TcpListener的正确而简单的实现,请参阅此链接。

https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener(v=vs.110).aspx