我正在尝试学习网络编程,并且正在尝试创建 TCP 服务器和 TCP 客户端。
服务器将启动并侦听连接。客户端将连接并向服务器发送一个字符串。然后服务器将回复一个包含接收到的字符串的字符串。
我面临的问题是,第一次尝试这是可行的,但之后有时客户会收到一个空回复。
下面是服务器的代码:
public void handlerThread()
{
TcpClient TcpClient = clients[clients.Count - 1];
NetworkStream networkStream = TcpClient.GetStream();
int i = -1;
while (TcpClient.Connected )
{
Byte[] data = new Byte[1024];
if ((i=networkStream.Read(data, 0, data.Length)) != 0)
{
string incomingMessage = Encoding.ASCII.GetString(data);
Debug.WriteLine("DDB Server incomingMessage: " + incomingMessage);
this.Invoke((MethodInvoker)(() => lbMessage.Items.Add("Message received is: " + incomingMessage)));
// Send back a response.
data = new Byte[1024];
string outMessage = string.Empty;
outMessage = "Recieved msg: " + incomingMessage;
data = System.Text.Encoding.ASCII.GetBytes(outMessage);
networkStream.Write(data, 0, data.Length);
Debug.WriteLine("DDB Server Reply: " + outMessage);
this.Invoke((MethodInvoker)(() => lblStatus.Text = "Sent reply!"));
}
}
}
客户端代码:
private void button2_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(_txtBoxMsg.Text))
{
try
{
Byte[] data = System.Text.Encoding.ASCII.GetBytes(_txtBoxMsg.Text);
stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
Debug.WriteLine("DDB Client Message: " + _txtBoxMsg.Text);
data = new Byte[1024];
String responseData = String.Empty;
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Debug.WriteLine("DDB Client recieved: " + responseData);
lbMsgs.Items.Add(string.Format("Received: {0}", responseData));
}
catch (ArgumentNullException ex)
{
MessageBox.Show("ArgumentNullException: " + ex); ;
}
catch (SocketException ex)
{
MessageBox.Show("SocketException: " + ex);
}
}
else
MessageBox.Show("You did not enter a message to be sent to server!", "Please enter a message", MessageBoxButtons.OK);
}
我在使用 Debug.WriteLine() 第一次运行时注意到了一些事情,消息显示正确。之后,消息彼此相邻(好像我使用的是 Debug.Write())。 可能是消息的字节表示已损坏(例如返回字符或其他内容)?