我尝试在 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?
繁星淼淼
相关分类