0

在 tcp 标头数据包中,它们是一个提到数据包总大小的字段。我已经实现了我的服务器,它以以下方式监听多个客户端

int numberOfClientsYouNeedToConnect = int.Parse(Console.ReadLine());
        for (int i = 0; i < numberOfClientsYouNeedToConnect; i++)
        {
            Thread newThread = new Thread(new ThreadStart(Listeners));
            newThread.Start();
        }

public static void Listeners()
    {
        try
        {
            Socket socketForClient = tcpListener.AcceptSocket();

            if (socketForClient.Connected)
            {
                Console.WriteLine("Client : " + socketForClient.RemoteEndPoint + " is now connected to server.");
                NetworkStream networkStream = new NetworkStream(socketForClient);
                //networkStream.ReadTimeout = 30;
                System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream);
                System.IO.StreamReader streamReader = new System.IO.StreamReader(networkStream);

                while (true)
                {
                    string theString = streamReader.ReadLine();
                    //Console.WriteLine(theString);
                    byte[] input_stream = extra_function.ConvertHexToString(theString);
                    for (int i = 0; i < input_stream.Length; i++)
                    {
                       // Console.WriteLine("hi");
                        Console.Write(input_stream[i]);
                    }


                    if (theString != "exit")
                    {
                        // original message from client
                        Console.WriteLine("------------------------------------------------------------------------------");
                        Console.WriteLine("Message recieved from client(" + socketForClient.RemoteEndPoint + ") : " + theString);

                        // ASCII code for the message from client 
                        Console.Write("ASCII Code for message is : ");
                        foreach (char c in theString)
                        {
                            Console.Write(System.Convert.ToInt32(c) + " ");
                        }
                    }
                 }

但我的问题是服务器没有收到完整的数据包,它开始处理它,而数据包的其他部分稍后到来。那么如何更改我的代码以便服务器接收完整的数据包然后处理它。总包的大小包含在包头中。服务器应该等到它从客户端接收到这么多字节,或者等到一段时间才能获得完整的数据包。

4

1 回答 1

-1

你试过StreamReader.ReadToEnd()代替StreamReader.ReadLine()吗?

于 2013-08-21T11:30:08.517 回答