经过几次修复后,我仍然遇到一个令人讨厌的错误。我使用VS2013
的开发人员命令提示符调试和运行服务器,并使用VS 2013运行客户端。
首先,我运行服务器没有任何问题,但是,当我启动客户端时,将数据放在那里的textbox
中,然后单击“发送”问题。
这是指示问题的服务器端代码。
IPAddress ipaddr=IPAddress.Parse("127.0.0.1");
TcpListener serverSocket = new TcpListener(ipaddr,8002);
int requestCount = 0;
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(" >> Server Started");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> Accept connection from client");
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[10025];
//issue stems out of here although i changed bytes size and tried too
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());
}
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine(" >> exit");
Console.ReadLine();
编辑:提出建议后,我进行了更改:
byte[] bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);`
到
byte[] bytesFrom = new byte[clientSocket.ReceiveBufferSize];
networkStream.Read(bytesFrom, 0, bytesFrom.Length);
导致给出了屏幕截图,但没有收到来自客户端的数据。
错误(来自命令提示符):-
他们实际上在叫什么
valid value
。PS。抱歉,如果我在此处提供的代码过长,但有必要
最佳答案
您应该将receiveBuffer size指定为第三个参数,而不是clientSocket.ReceiveBufferSize
networkStream.Read(bytesFrom, 0, bytesFrom.Length);
或者
用clientSocket.ReceiveBufferSize创建一个缓冲区;
byte[] bytesFrom = new byte[clientSocket.ReceiveBufferSize];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
这是来自Microsoft的示例:
while(true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while((i = stream.Read(bytes, 0, bytes.Length))!=0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}
// Shutdown and end connection
client.Close();
}