英文:
Changing the port of a node.js websocket server
问题
我想要创建一个服务器,用于监听来自标准WebSocket和Socket.IO WebSocket的连接。分开的话,我可以让它们都在3000端口上工作,但如果它们都监听在同一端口上,它们就无法正常工作,标准WebSocket会抛出大量错误,所以我尝试让它们分别监听不同的端口,Socket.IO(使用Express服务器)监听在3000端口上,标准WebSocket监听在4000端口上:
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const socketIO = require('socket.io');
const app = express()
const expresServer = http.createServer(app);
// 创建Socket.IO实例并将其附加到Express
const io = socketIO(expresServer);
// 创建WebSocket服务器在端口4000上
const wss = new WebSocket.Server({ port: 4000 });
// WebSocket连接:
wss.on('connection', (ws) => {
console.log('新客户端WebSocket连接');
ws.on('message', (message) => {
console.log(`收到WebSocket消息:${message}`);
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(`你好,我收到了你的WebSocket消息:${message}`);
}
});
});
// 注册断开连接
ws.on('close', () => {
console.log('WebSocket客户端断开连接');
});
});
// Socket.IO连接:
io.on('connection', (socket) => {
console.log('新客户端Socket.IO连接');
socket.on('message', (message) => {
console.log(`收到Socket.IO消息:${message}`);
io.emit('message', `你好,我收到了你的Socket.IO消息:${message}`);
});
// 注册断开连接
socket.on('disconnect', () => {
console.log('Socket.IO客户端断开连接');
});
});
// 在3000端口上启动Express服务器
expresServer.listen(3000, () => {
console.log('Express服务器在3000端口上监听');
});
但是,当我尝试使用Poco C++连接到标准WebSocket时,它现在会引发Net异常。我只是更改了端口,所以不知道为什么不起作用。我从未打开过3000端口,所以没有理由打开4000端口,对吗?
这是用于连接Poco C++的C++客户端:
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/HTTPMessage.h"
#include "Poco/Net/WebSocket.h"
#include "Poco/Net/HTTPClientSession.h"
#include <iostream>
using Poco::Net::HTTPClientSession;
using Poco::Net::HTTPRequest;
using Poco::Net::HTTPResponse;
using Poco::Net::HTTPMessage;
using Poco::Net::WebSocket;
int main(int args, char **argv)
{
HTTPClientSession cs("192.168.50.122", 4000);
HTTPRequest request(HTTPRequest::HTTP_GET, "/?encoding=text", HTTPMessage::HTTP_1_1);
request.set("origin", "Cliente");
HTTPResponse response;
try {
WebSocket* m_psock = new WebSocket(cs, request, response);
std::string text = "Hello, world!";
auto len = m_psock->sendFrame(text.c_str(), text.length(), WebSocket::FRAME_TEXT);
int flags = 0;
char receiveBuff[256];
int rlen = m_psock->receiveFrame(receiveBuff, 256, flags);
std::cout << receiveBuff << std::endl;
m_psock->close();
delete m_psock;
}
catch (std::exception &e) {
std::cout << "异常 " << e.what();
}
}
希望这可以帮助你解决问题。如果你有任何进一步的问题,请随时提问。
英文:
I want to create a server listening for conections from standard websockets and socket.io websockets. Separately I can make them work just on the 3000 port but if both listen on that port then it just does not work, the standard websockets throw a lot of errors, so I was trying to make them listen on different ports, the socket.io (With an express server) on port 3000 and the standard websockets on 4000:
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const socketIO = require('socket.io');
const app = express()
const expresServer = http.createServer(app);
// Create socket.io instance and attach it to express
const io = socketIO(expresServer);
// Create websocket server on port 3000
const wss = new WebSocket.Server({ port: 4000 });
// WS connections:
wss.on('connection', (ws) => {
console.log('Nuevo cliente WebSocket conectado');
ws.on('message', (message) => {
console.log(`Recibido mensaje de WebSocket: ${message}`);
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(`Hola, recibí tu mensaje de WebSocket: ${message}`);
}
});
});
// Register diconect
ws.on('close', () => {
console.log('Cliente WebSocket desconectado');
});
});
// Socket.io connections:
io.on('connection', (socket) => {
console.log('Nuevo cliente Socket.io conectado');
socket.on('message', (message) => {
console.log(`Recibido mensaje de Socket.io: ${message}`);
io.emit('message', `Hola, recibí tu mensaje de Socket.io: ${message}`);
});
// Register diconect
socket.on('disconnect', () => {
console.log('Cliente Socket.io desconectado');
});
});
// Launch Express server on 3000
expresServer.listen(3000, () => {
console.log('Express server listening on 3000');
});
But when I try to connect with POCO C++ to the standard websockets it gives a Net Exception now. I just changed the port so I do not know why it does not work. I never opened the 3000 port so there is no reason to open 4000, is it?
This is the C++ client to connect with POCO C++:
#include "Poco/Net/HTTPRequest.h"
#include "Poco/Net/HTTPResponse.h"
#include "Poco/Net/HTTPMessage.h"
#include "Poco/Net/WebSocket.h"
#include "Poco/Net/HTTPClientSession.h"
#include <iostream>
using Poco::Net::HTTPClientSession;
using Poco::Net::HTTPRequest;
using Poco::Net::HTTPResponse;
using Poco::Net::HTTPMessage;
using Poco::Net::WebSocket;
int main(int args,char **argv)
{
HTTPClientSession cs("192.168.50.122",4000);
HTTPRequest request(HTTPRequest::HTTP_GET, "/?encoding=text",HTTPMessage::HTTP_1_1);
request.set("origin", "Cliente");
HTTPResponse response;
try {
WebSocket* m_psock = new WebSocket(cs, request, response);
std::string text = "Hello, world!";
auto len = m_psock->sendFrame(text.c_str(), text.length(), WebSocket::FRAME_TEXT);
int flags=0;
char receiveBuff[256];
int rlen=m_psock->receiveFrame(receiveBuff,256,flags);
std::cout << receiveBuff << std::endl;
m_psock->close();
delete m_psock;
} catch (std::exception &e) {
std::cout << "Exception " << e.what();
}
}
答案1
得分: 1
这是我使它工作的方式:
import { createServer } from "http";
import { Server } from "socket.io";
const server = createServer();
const server1 = createServer();
const io = new Server(server, {
// 选项
});
const io1 = new Server(server1, {
// 选项
});
const sockets = [io, io1];
sockets.forEach((socket) => {
socket.on("connection", (clientSocket) => {
// ...
});
});
server.listen(3000, () => console.log("监听端口 3000"));
server1.listen(4000, () => console.log("监听端口 4000"));
这只是一个尝试,所以你可以根据更好的编程体验重命名所有变量。
为使导入工作,你需要在 package.json 中添加 "type": "module",
或者转换为 commonjs/require。
英文:
This is how I made it work:
import { createServer } from "http";
import { Server } from "socket.io";
const server = createServer();
const server1 = createServer();
const io = new Server(server, {
// options
});
const io1 = new Server(server1, {
// options
});
const sockets = [io, io1];
sockets.forEach((socket) => {
socket.on("connection", (clientSocket) => {
// ...
});
});
server.listen(3000, () => console.log("listening on port 3000"));
server1.listen(4000, () => console.log("listening on port 4000"));
This was a try, so you can rename all variables for better programming experience.
For import to work, you need to add "type": "module",
to package.json, or convert to commonjs/require.
答案2
得分: 0
你可以创建多个服务器,每个服务器监听不同的端口。
英文:
You can create multiple servers and each listen on different ports.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论