在c++和node.js(服务器)之间建立套接字通信的困难

我尝试在 C++ 和 node.js 服务器之间建立套接字通信。这是我的 index.js 代码:


'use strict';


const express     = require('express');

const app         = express();

const serverHttp  = require('http').Server(app); 

const io = require('socket.io')(serverHttp);


const port = 8081;


io.on('connection', function (socket) {   

    socket.on('message', function (data) {

        console.log("key received!!!" + data);

    socket.emit('server', 'hello socket io');

        console.log("sent server msg");

    });

});


serverHttp.listen(port, function() {  

    console.log("init!!!");    

});

这是我编译成功的 C++ 代码:


#include <stdio.h>

#include <stdlib.h>

#include <assert.h>


#ifdef _WIN32

#include <winsock2.h>

#include <ws2tcpip.h>

#else

#include <string.h>

#include <unistd.h>

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <netdb.h>

#endif


#ifdef _WIN32

#define close(sockdep) closesocket(sockdep)

#define perror(errmsg) { fprintf(stderr, "%s: %d\n", (errmsg), WSAGetLastError()); }

#endif


#define net_assert(err, errmsg) { if ((err)) { perror(errmsg); assert(!(err)); } }


#define SERVER "localhost"

#define PORT 8081

#define BLEN 128


int

main(int argc, char *argv[])

{

  struct sockaddr_in server;

  struct hostent *sp;

  int sd;

  int n;

  char buf[BLEN];

#ifdef _WIN32

  int err;

  WSADATA wsa;

  extern int write();

  

  err = WSAStartup(MAKEWORD(2,2), &wsa);  // winsock 2.2

  net_assert(err, "sample client: WSAStartup");

#endif

  } 


 

我的环境是 Mac,我正在使用 Xcode 来编译 c++。我将节点连接node index.js到本地主机,还编译并运行了 C++ 程序。但是,当我打开 localhost:8081 时,我在控制台中收到此错误:


GET http://localhost:8081/ 404 (Not Found)        localhost/:1 


Refused to load the image 'http://localhost:8081/favicon.ico' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.            localhost/:1

我对编程很陌生,如果你能澄清什么是错的,我将不胜感激。我无法识别 C++ 中的发送和接收代码在哪里,因为它与 JavaScript 有很大不同。那么,我怎样才能构建一个简单的通信,我只想将一个数组从 C++ 发送到 index.js?


函数式编程
浏览 115回答 1
1回答

繁星淼淼

您的方法无法工作,因为socket.io是一种定义为与其他 socket.io 客户端或服务器一起使用的协议,而在 C++ 中创建的原始 TCP 套接字将与其他 TCP 套接字一起使用。您在 C++ 代码中创建的是一个 TCP 套接字,遗憾的是它与 socket.io 使用的内容无关。Socket.io 支持使用 HTTP 流或 WebSocket(另一种协议)进行通信。这是一个似乎实现了 socket.io 协议的 C++ 库示例。我自己从未使用过它,但这似乎是您正在寻找的东西。尝试在 C++ 端使用它,或在 node.js 端实现原始 tcp 套接字。这个库可能很适合。我推荐本教程让您开始了解直接使用 C++ 实现客户端-服务器通信的基础知识,然后您可以从那里开始了解如何在 nodejs 中创建客户端。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript