NetworkStream.Read()不起作用并抛出ArgumentOutOfRangeException

时间:2016-11-18 17:02:47

标签: c# sockets tcp client-server chat

只是尝试创建聊天服务器客户端

  1. 这是等待客户端连接的服务器(可选)*

        TcpListener serverSocket = new TcpListener(8888);
        int requestCount = 0;
        TcpClient clientSocket = default(TcpClient);
        serverSocket.Start();
        Console.WriteLine(" >> Server Started");
        clientSocket = serverSocket.AcceptTcpClient();
        Console.WriteLine(" >> Accept connection from client");
    
  2. 然后,客户端连接到服务器(可选)*

        System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
        clientSocket.Connect("127.0.0.1", 8888);
    
  3. 然后,在客户端,我从Windows窗体发送消息,按钮单击事件执行此操作:

    NetworkStream serverStream = clientSocket.GetStream();
    byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text + "$");
    serverStream.Write(outStream, 0, outStream.Length);
    serverStream.Flush();
    //this goes to the server  ------> to the part (4)
    
    //returning from the server <------
    byte[] inStream = new byte[10025];
    serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
    string returndata = System.Text.Encoding.ASCII.GetString(inStream);
    textBox2.Text = "";
    textBox2.Focus();
    
  4. 最后,在服务器端,客户端请求的无限bucle。这是我在networkStream.Read()

    上遇到问题的地方
    while ((true))
        {
            try
            {
                requestCount = requestCount + 1;
                NetworkStream networkStream = clientSocket.GetStream();
                byte[] bytesFrom = new byte[10025];
                if (networkStream.DataAvailable)
                {
                    **networkStream.Read(bytesFrom, 0, (int) clientSocket.ReceiveBufferSize);**
                    string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                    dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
                    Console.WriteLine(" >> Data from client - " + dataFromClient);
                    string serverResponse = "Last Message from client" + dataFromClient;
                    Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
                    networkStream.Write(sendBytes, 0, sendBytes.Length);
                    networkStream.Flush();
                    Console.WriteLine(" >> " + serverResponse);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    
  5. 我一步一步地调试(在服务器和客户端上),直到我进入networkStream.Read()方法并且抛出ArgumentOutOfRangeException ...然后,任何人都帮助我或告诉我错误在哪里。

    *我说可选,因为1.和2.步骤很好(至少,我认为)

1 个答案:

答案 0 :(得分:3)

MSDN开始,ArgumentOutOfRangeException意味着偏移计数为负(第2和第3个参数),或者&#34;大小(计数) &#34;参数大于缓冲区长度减去&#34;偏移量&#34;参数。

我尝试传递bytesFrom.Length而不是clientSocket.ReceiveBufferSize