我正在尝试编写一个简单的功能回声套接字客户端/服务器。我已经设法让一个带有客户端的同步服务器工作,但现在我需要一个异步服务器。
如果我使用 Microsoft 的版本,它运行良好,异步服务器:
https://msdn.microsoft.com/en-us/library/fx6588te(v=vs.110).aspx
微软异步客户端:
https://msdn.microsoft.com/en-us/library/bew39x2a(v=vs.110).aspx
我现在尝试的是让Microsoft Async Client与Linux 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 客户端告诉我该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 服务器时有效,但不是 Overlapped I/O 服务器,所以实际上我要求在Overlapped I/O 服务器代码中更改什么,以便它发回 ASync 客户端的消息能收到吗?
Hello World
如果从 ASync 客户端发送,这是服务器的输出:
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