C#套接字 - 如何保持套接字打开?

时间:2012-07-21 05:20:46

标签: c# loops stream

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

    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.");
        }
    }

1 个答案:

答案 0 :(得分:3)

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