-3
我有这段代码。我可以成功地从我的客户端接收数据,但只有一次。在我收到数据一次后,如果客户端试图发送更多的服务器没有收到它。谁能帮忙?C#套接字 - 如何保持套接字打开?
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.");
}
}
保护您的产品!怎么分享知识?怎么样拯救Karl-JohanSjögren时间他可能会浪费回答你的问题? – 2012-07-21 05:50:13
a)通过点击“编辑”链接,您的原始代码仍然可见。 b)StackOverflow上所有用户生成的内容均获得Creative Commons许可。 c)在这些情况下,建议创建一个最小可重现的示例 - 即删除与该问题无关的任何代码部分,确保问题仍然存在,然后发布该代码。 – 2012-07-21 06:13:45
对不起,你是对的。我重新添加了代码:) – DannyF247 2012-07-21 07:30:05