-2

我有这个代码。我可以成功接收来自客户的数据,但只能接收一次。在我收到一次数据后,如果客户端尝试再发送一次,服务器就没有收到它。任何人都可以帮忙吗?

    private void startListening()
    {
        TcpListener server = null;


        try
        {

            server = new TcpListener(IPAddress.Parse("127.0.0.1"), 7079);

            server.Start();

            Byte[] bytes = new Byte[256];
            String data = null;

            //Enter listening loop
            while (true)
            {

                addLog("Waiting for push.");

                TcpClient client = server.AcceptTcpClient();
                addLog("Push request received, accepted.");

                data = null;

                NetworkStream stream = client.GetStream();

                int i;

                //Loop to receive all data
                while((i = stream.Read(bytes, 0, bytes.Length))!=0)
                {
                    //Translate data bytes to ASCII string
                    data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);

                    //Process data
                    data = data.ToUpper();

                    byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                    //send response
                    stream.Write(msg, 0, msg.Length);
                    addLog("Received: '" + data + "'");
                }

                //End ALL Connections
                client.Close();
                server.Stop();
            }
        }
        catch(SocketException e)
        {
            addLog("SocketException: " + e);
        }
        finally
        {
            //Stop listening for new clients
            MessageBox.Show("Finished.");
        }
    }
4

1 回答 1

4

您将在循环结束时关闭服务器和客户端 ( server.Stop();)。您的外部循环将继续运行并尝试从您的服务器获取一个新的 TcpClient (这意味着建立了一个新的连接),但是由于您已经停止了服务器,所以这将永远不会发生(或者可能会引发异常)。

于 2012-07-21T05:27:58.063 回答