我在程序中继承了 CSocket 类来接收和发送消息,在 OnReceive 函数中写了 Receive 函数用来接收消息,并添加了多个方法用来发送消息。大概的结构如下伪代码所示:(一些定义的常数未展示)
我的问题是:
- 我查阅资料得到的结论是 CSocket 类是同步且是阻塞的。我理解为在执行 Receive 和 Send 函数时会线程会发生阻塞。那么我在主函数中创建了一个 MySocket 类之后,如果收到了消息或者我直接调用了 SendControlMessage 和 SendTextData 发送消息,阻塞了哪个线程?
- 在 OnReceive 中调用 Receive 函数,因为 OnReceive 函数是一个回调函数,那这不就是一种异步模式了么?
// MySocket.h 头文件
class MySocketL : public CSocket{
void OnReceive(int errcode);
void SendControlMessage(int type); // 发送控制数据
void SendTextData(Mesg mesg); // 发送文本信息
}
//MySocket.cpp 文件
void MySocket::OnReceive(int errcode)
{
wchar_t data[PACKET_SIZE] = { 0 };
Receive(data, length);
if(...) {
SendControlMessage(...);
}
else {
SendTextData(...);
}
}
void MySocket::SendControlMessage(int type)
{
wchar_t packet[PACKET_SIZE] = { 0 };
packet[0] = type;
Send(packet, sizeof(packet));
}
void MySocket::SendTextData(Mesg mesg)
{
wchar_t packet[PACKET_SIZE] = { 0 };
packet[0] = TYPE_TEXT;
memcpy(&packet[1], &mesg, sizeof(mesg));
Send(packet, sizeof(packet));
}