只是尝试创建聊天服务器客户端
这是等待客户端连接的服务器(可选)*
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");
然后,客户端连接到服务器(可选)*
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
clientSocket.Connect("127.0.0.1", 8888);
然后,在客户端,我从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();
最后,在服务器端,客户端请求的无限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());
}
}
我一步一步地调试(在服务器和客户端上),直到我进入networkStream.Read()方法并且抛出ArgumentOutOfRangeException ...然后,任何人都帮助我或告诉我错误在哪里。
*我说可选,因为1.和2.步骤很好(至少,我认为)
答案 0 :(得分:3)
从MSDN开始,ArgumentOutOfRangeException意味着偏移或计数为负(第2和第3个参数),或者&#34;大小(计数) &#34;参数大于缓冲区长度减去&#34;偏移量&#34;参数。
我尝试传递bytesFrom.Length
而不是clientSocket.ReceiveBufferSize
。