问题
Just trying to create a chat server-client
This is the server waiting for a client connection (optional)*
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");
Then, the client connects to the server (optional)*
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient(); clientSocket.Connect("127.0.0.1", 8888);
Then, on the client side, I send the message from a windows form, and the button click event does this:
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();
Finally, on the server side, an infinite bucle for client requests. And here is where I got the problem on the 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()); } }
I debugged step by step (on server and client), and it's all fine until I get to the networkStream.Read() method, and throws ArgumentOutOfRangeException... Please, anybody help me or tell me where the error is.
*I say optional because the 1. and 2. steps are fine (at least, I think)
回答1:
From the MSDN, ArgumentOutOfRangeException means that offset or count is negative(2nd and 3rd parameters), OR the "size(count)" parameter is greater than the length of buffer minus the value of the "offset" parameter.
I'd try passing bytesFrom.Length
as opposed to clientSocket.ReceiveBufferSize
.
来源:https://stackoverflow.com/questions/40682437/networkstream-read-doesnt-work-and-throws-argumentoutofrangeexception