gpt4 book ai didi

c# - 第二次尝试时 TcpClient 无法读取

转载 作者:太空宇宙 更新时间:2023-11-03 13:17:32 25 4
gpt4 key购买 nike

我在收到一次后尝试第二次阅读时遇到了问题。我相信写入已排队,只有在我停止应用程序时才会通过。不知何故,在第一次阅读后,即使阅读了整条消息,我也会阻止。我的目标是读取传入的消息,对其进行处理,然后将消息发送到连接的客户端,然后期望客户端返回一条消息,确认它收到了消息。这是我到目前为止的代码

我在一个单独的线程上启动一个监听器来等待客户

        this.tcpListener = new TcpListener(IPAddress.Loopback, 14000);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();

然后在客户端连接后,我将通信处理交给另一个线程

        this.tcpListener.Start();
tcpClient = this.tcpListener.AcceptTcpClient();
Thread clientThread = new Thread(new ParameterizedThreadStart(ProcessMessage));
clientThread.Start(tcpClient);

ProcessMessage 方法如下所示

public void ProcessMessage(object client)
{
if (client != null)
{
tcpClient = client as TcpClient;
}

this.messageReceived = false;

NetworkStream clientReadStream = tcpClient.GetStream();


byte[] message = new byte[tcpClient.ReceiveBufferSize];
int byteRead = 0;

while (!this.messageReceived)
{
byteRead = 0;
if (tcpClient.Connected)
{
try
{
byteRead = clientReadStream.Read(message, 0, tcpClient.ReceiveBufferSize);
}
catch (Exception)
{
throw;
}

if (byteRead == 0)
{

break;
}
else
{
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
this.request = encoder.GetString(message, 0, byteRead);
if (!string.IsNullOrEmpty(this.request))
{
this.messageReceived = true;
}

}
}
}
}

处理消息后,我需要将消息发送回客户端,我通过名为 SendData 的方法从不同的线程执行此操作

 public void SendData(string data)
{
if (tcpClient != null)
{

if (tcpClient.Connected)
{
try
{
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
NetworkStream clientWriteStream = tcpClient.GetStream();

byte[] buffer = encoder.GetBytes(data);
clientWriteStream.Write(buffer, 0, buffer.Length);
clientWriteStream.Flush();

this.messageReceived = false;

}
catch
{
throw;
}
}
}

}

不确定要看什么方向..感谢您提前提出任何建议或指示

最佳答案

你正在设置 this.messageReceived = true;当您收到消息时,条件是 while (!this.messageReceived),这是因为当收到第一条消息时,您收到 while 将终止...

试试这段代码:

public void ProcessMessage(object client)
{
if (client != null)
{
tcpClient = client as TcpClient;
}

this.messageReceived = false;

NetworkStream clientReadStream = tcpClient.GetStream();


byte[] message = new byte[tcpClient.ReceiveBufferSize];
int byteRead = 0;

while (true)
{
byteRead = 0;
if (tcpClient.Connected)
{
try
{
byteRead = clientReadStream.Read(message, 0, tcpClient.ReceiveBufferSize);
}
catch (Exception)
{
throw;
}

if (byteRead == 0)
{

break;
}
else
{
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
this.request = encoder.GetString(message, 0, byteRead);
if (!string.IsNullOrEmpty(this.request))
{
this.messageReceived = true;
}

}
}
}
}

注意这部分代码:

   if (byteRead == 0)
{

break;
}
else ...

因为如果 Read 方法没有读取任何东西 while again 将终止...

关于c# - 第二次尝试时 TcpClient 无法读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25538713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com