Node.js到c ++客户端:没有从socket.emit接收消息

时间:2017-07-18 07:28:36

标签: c++ node.js sockets

我正在尝试在c ++客户端和node.js服务器之间进行通信。我可以将数据发送到服务器,但我无法将任何消息发送回客户端。我对socket.emit的简单理解是它应该通过在基本的Windows消息循环中调用FD_READ消息上的recv()来发送可检索的消息。我可能会遗漏那些东西。

以下是相关的客户端代码:

s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (s == INVALID_SOCKET)
{
    MessageBox(hwnd, TEXT("3"), TEXT(""), MB_OK | MB_ICONEXCLAMATION);
    return 0;
}

long hostname = inet_addr("192.168.1.70");
target.sin_family = AF_INET;
target.sin_port = htons(server_port_num);
target.sin_addr.s_addr = hostname;

if (connect(s, (SOCKADDR *)&target, sizeof(target)) == SOCKET_ERROR)
{
    MessageBox(hwnd, TEXT("999"), TEXT(""), MB_OK | MB_ICONEXCLAMATION);
    return 0;
}

WSAAsyncSelect(s, hwnd, CUST_MSG, FD_READ | FD_CONNECT | FD_CLOSE);

我发送的数据是在服务器控制台上接收和输出的:

int nret = send(s, buffer, strlen(buffer), 0);

然后我尝试在接收数据的同一服务器事件中发回一些数据:

this.socket.on('data', function (buffer) {
    try {
        logger.warn(buffer + "\n");
        socket.emit('message', 'psst, wanna buy some macaroni?');
        //that.messageHandler(that, buffer);
    } catch (err) {
        logger.warn('Protocol ' + err + ' ' + that.socket.remoteAddress);
        that.dispose();
    }
});

我有一个消息循环,但它没有检测到从socket.emit()发送的消息:

MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0)
{
    if (numBytes > 0) {
        wchar_t buffer[256];
        wsprintfW(buffer, L"%d", numBytes);
        MessageBox(hwnd, buffer, TEXT(""), MB_OK | MB_ICONEXCLAMATION);
    }

    TranslateMessage(&msg);
    DispatchMessage(&msg);

}

//MESSAGE LOOP FUNCTION:
LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message) //handle the messages
{
case CUST_MSG: //Is a message being sent?
{
    switch (lParam) //If so, which one is it?
    {
    case FD_ACCEPT:
        MessageBox(hwnd, TEXT("accept"), TEXT(""), MB_OK | MB_ICONEXCLAMATION);
        accept(wParam, NULL, NULL);
        break;
    case FD_CONNECT:
        MessageBox(hwnd, TEXT("connect"), TEXT(""), MB_OK | MB_ICONEXCLAMATION);
        break;
    case FD_READ:
        char buffer[80];
        int byte_num;
        memset(buffer, 0, sizeof(buffer));
        byte_num = recv(wParam, buffer, sizeof(buffer) - 1, 0);
        MessageBox(hwnd, TEXT("READING"), TEXT(""), MB_OK | MB_ICONEXCLAMATION);

        numBytes += byte_num;
        break;
    case FD_CLOSE:
        //MessageBox(hwnd, TEXT("close"), TEXT(""), MB_OK | MB_ICONEXCLAMATION);
        break;
    }
}

当我稍微更改程序并将数据从客户端发送到客户端时,相同的循环正确检测到消息。我已经尝试过使用bind(),listen(),recv(),但我无法使用node获取FD_READ消息。我试过在同一台计算机上运行的客户端和服务器,以及同一本地网络上的不同计算机。

1 个答案:

答案 0 :(得分:-1)

要将数据写入Node.js中的套接字,请使用socket.write()

请参阅https://nodejs.org/api/net.html#net_socket_write_data_encoding_callback