我有这段代码。我可以成功地从我的客户端接收数据,但只能接收一次。在我收到一次数据后,如果客户端试图再发送,服务器就没有收到数据。有人能帮忙吗?
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.");
}
}
您将在循环(server.Stop();
)结束时关闭服务器和客户端。您的外循环将继续进行,并尝试从服务器获取一个新的TcpClient(这意味着建立了一个新连接),但由于您已经停止了服务器,因此这种情况永远不会发生(或者可能引发异常)。