gpt4 book ai didi

c# - 如何阻止我的程序卡住 TCP 连接 C#

转载 作者:可可西里 更新时间:2023-11-01 02:50:27 24 4
gpt4 key购买 nike

我已经创建了一个 TCP 客户端,它连接正常,但我有点困惑如何在不关闭连接的情况下从服务器接收消息?

我目前的方法是通过网络流读取方法运行协同例程,但这会卡住我的程序,所以这显然是错误的方法,所以我不确定如何修复它。

我想保持连接事件并在消息从服务器到达时读取消息。

这是我目前设置的:

// the idea is to run a coroutine for recieving messages
private IEnumerator<float> _RunTCPSocket()
{
int timer = DateTime.Now.Second;
byte[] readBuffer = new byte[1024];

while (SocketManager.IsConnected)
{
// this is the keep alive packets to server to prevent timeout on server side
if (DateTime.Now.Second - timer > KeepAliveRate)
{
Debug.Log("Sending");
timer = DateTime.Now.Second;
SocketManager.Send(null);
}

int msgLength = SocketManager.Recieve(readBuffer);
if (msgLength > 0)
Debug.Log(Encoding.ASCII.GetString(readBuffer, 0, msgLength));

yield return Timing.WaitForOneFrame;
}
}

这是接收方法的代码:

    public int Recieve(byte[] readBuffer)
{
if (!IsConnected)
return -1; //-1 signifies an error aka we are disconnected

try
{
// NetworkStream is from TcpClient.GetStream()
bytesRead = _networkStream.Read(readBuffer, 0, readBuffer.Length);
}
catch (Exception e)
{
IsConnected = false;
Debug.Log(e);
bytesRead = -1;
}

return bytesRead;
}

我如何防止它锁定我的程序?

最佳答案

您可以使用 Begin/End 方法让您的程序负责:

Document from microsoft

可以看到BeginReceive方法的使用非常复杂,个人觉得不太好用。
另一种方法是在任务中调用读/写方法。
第三个选项是使用在客户端使用的TcpClient 和在服务器端使用的TcpListener。这两个类只是下划线 TCP 套接字的包装器。这些包装器可以让您使用 Stream 和 Async 方法更轻松。

如果您想了解有关使用 C# 进行网络编程的更多信息,我强烈推荐这本书:
C# 网络编程 作者:Richard Blum

更新

使用任务的代码:

    public event EventHandler<ReceiveDataEventArgs> DataReceived = null;
public void StartReceive()
{
Task.Run(() =>
{
while (true)
{
var bytesRead = _networkStream.Read(readBuffer, 0, readBuffer.Length);
DataReceived?.Invoke(this, new ReceiveDataEventArgs
{
Data = bytesRead
});
}
});

}

public class ReceiveDataEventArgs : EventArgs
{
public byte[] Data { get; set; }
}

关于c# - 如何阻止我的程序卡住 TCP 连接 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47383083/

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