我有这个代码。我可以成功接收来自客户的数据,但只能接收一次。在我收到一次数据后,如果客户端尝试再发送一次,服务器就没有收到它。任何人都可以帮忙吗?
private void startListening()
{
TcpListener server = null;
try
{
server = new TcpListener(IPAddress.Parse("127.0.0.1"), 7079);
server.Start();
Byte[] bytes = new Byte[256];
String data = null;
//Enter listening loop
while (true)
{
addLog("Waiting for push.");
TcpClient client = server.AcceptTcpClient();
addLog("Push request received, accepted.");
data = null;
NetworkStream stream = client.GetStream();
int i;
//Loop to receive all data
while((i = stream.Read(bytes, 0, bytes.Length))!=0)
{
//Translate data bytes to ASCII string
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
//Process data
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
//send response
stream.Write(msg, 0, msg.Length);
addLog("Received: '" + data + "'");
}
//End ALL Connections
client.Close();
server.Stop();
}
}
catch(SocketException e)
{
addLog("SocketException: " + e);
}
finally
{
//Stop listening for new clients
MessageBox.Show("Finished.");
}
}