我在C#中完成了客户端 - 服务器语音聊天(如ventrilo),现在我正在使用非托管的win32 c ++。我有一个关于如何在c ++中处理异步读/写的问题。在C#中,一旦完成BeginSend / BeginRecieve,你就有一个被调用的函数(EndSend / EndRecieve)。这是如何在c ++中完成的?我看了msdn并用Google搜索,找不到一件衣服。
以下是按下按钮时运行的代码,触发调用此函数的WM_WRITE消息:
[...]
case ID_BUTTON_SEND:
SendMessage(hWnd,SOCKET_TCP,0,FD_WRITE);
break;
[....]
case FD_WRITE:
onTextSend()
break;
[....]
void onSendText(HWND hWnd) {
// get window handle to send edit control
HWND hWndSend = GetDlgItem(hWnd,ID_EDIT_SEND);
// get textlength of send edit control
int textlen = GetWindowTextLength(hWndSend);
// allocate memory for a buffer that will contains the text to be sent and get the text
char* textbuff = (char*)malloc(textlen+1);
SendMessage(hWndSend,WM_GETTEXT,textlen+1,(LPARAM)textbuff);
// send content
send(tcp_sock,textbuff,textlen+1,0);
// cleanup allocated tempbuffer
free(textbuff);
}
当然我不想发起异步发送,然后继续直接释放发送中使用的缓冲区,我想在发送完成后解除分配(如EndSend)。我没有找到c ++的方法来做,有什么建议吗?
编辑:还有!出于某种原因,当服务器接受客户端时,客户端没有收到FM_CONNECT消息,是否应该在客户端连接后立即获取它?我可以发送()和recv(),所以连接肯定是up。
答案 0 :(得分:3)
看看Boost Asio library。即使您不需要跨平台解决方案,Asio也是很棒的C ++ 提供异步套接字的库。 an example of asynchronous read/write
答案 1 :(得分:2)
如果你不想处理Asio,这里有关于异步套接字的好教程:http://www.gamedev.net/reference/programming/features/asyncsock/