【发布时间】:2024-12-29 18:50:02
【问题描述】:
我有这个代码。我可以成功接收来自客户的数据,但只能接收一次。在我收到一次数据后,如果客户端尝试再发送一次,服务器就没有收到它。有人可以帮忙吗?
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-Johan Sjögren 可能浪费在回答您的问题上的时间怎么样?
-
a) 通过单击“已编辑”链接,您的原始代码仍然可见。 b) * 上的所有用户生成内容均根据知识共享许可进行许可。 c) 在这种情况下,建议创建一个最小可重现的示例——即删除与问题无关的任何代码部分,确保问题仍然存在,然后发布该代码。
-
对不起,你们都说得对。我重新添加了代码:)