gpt4 book ai didi

c# - Linux 重叠 I/O TCP 套接字服务器未正确响应 C# 异步客户端

转载 作者:太空宇宙 更新时间:2023-11-04 10:53:37 25 4
gpt4 key购买 nike

我正在尝试编写一个功能简单的回声套接字客户端/服务器。我已经设法让带有客户端的同步服务器正常工作,但现在我需要一个异步服务器。

如果我使用 Microsoft 的版本,它运行良好,ASync Server:

https://msdn.microsoft.com/en-us/library/fx6588te(v=vs.110).aspx

Microsoft ASync 客户端:

https://msdn.microsoft.com/en-us/library/bew39x2a(v=vs.110).aspx

我现在正在尝试的是让 Microsoft Async ClientLinux C++ Overlapped I/O Server 通信:

http://www.tutorialized.com/tutorial/Linux-C-Overlapped-Server-and-Client-Socket-Example/77220

问题从这里开始。连接已建立,我可以向服务器发送消息,服务器响应回显消息(根据调试和终端输出),但 Microsoft ASync 客户端永远不会在其套接字上收到响应。

是否无法将异步客户端连接到重叠 I/O 服务器?我不确定为什么服务器的回复永远不会到达客户端。调试 Microsoft ASync Client 告诉我 Receive 函数从未通过这行代码:

receiveDone.WaitOne();

receiveDone 是一个 ManualResetEvent:

private static ManualResetEvent receiveDone =
new ManualResetEvent(false);

上下文:

// Receive the response from the remote device.
Receive(client);
receiveDone.WaitOne();

这里是接收回调函数,完成后设置receiveDone。 bytesRead 永远不会超过 0.:

private void ReceiveCallback(IAsyncResult ar)
{
try
{
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;

// Read data from the remote device.
int bytesRead = client.EndReceive(ar);

if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

// Get the rest of the data.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
else
{
// All the data has arrived; put it in response.
if (state.sb.Length > 1)
{
response = state.sb.ToString();
}
// Signal that all bytes have been received.
receiveDone.Set();
}
}
catch (Exception e)
{
msg("Fail ReceiveCallback: " + e.Message, false);
}
}

无论如何,此代码在连接到 ASync Server 时有效,但在 Overlapped I/O 服务器时无效,所以实际上我是在询问要在 Overlapped I/O server code 中更改的内容, 以便它发回 ASync 客户端可以接收的消息?

如果从 ASync 客户端发送 Hello World,这是服务器的输出:

root@deb7sve:/home/petlar/Host/SockServer# g++ OverlappedServer.cpp -o os.out -lpthread
root@deb7sve:/home/petlar/Host/SockServer# ./os.out
---------------------
Received connection from 10.0.2.2
Read 13 bytes from 4
Sent 13 bytes to 4

最佳答案

该客户端代码仅在连接关闭时设置事件。根据您的评论,服务器不会关闭连接。这就是从未设置事件的原因。

扔掉客户端代码并使用简单的同步代码重写它。 50% 的代码用于制作异步 IO(以一种不正常的方式)。 Async IO 不是为了提高网络效率。它是为了节省线程资源。客户端可能不需要它。

关于c# - Linux 重叠 I/O TCP 套接字服务器未正确响应 C# 异步客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29730621/

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