更改Node.js WebSocket服务器的端口

huangapple go评论75阅读模式
英文:

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(&#39;express&#39;);
const http = require(&#39;http&#39;);
const WebSocket = require(&#39;ws&#39;);
const socketIO = require(&#39;socket.io&#39;);
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(&#39;connection&#39;, (ws) =&gt; {
console.log(&#39;Nuevo cliente WebSocket conectado&#39;);
ws.on(&#39;message&#39;, (message) =&gt; {
console.log(`Recibido mensaje de WebSocket: ${message}`);
wss.clients.forEach((client) =&gt; {
if (client.readyState === WebSocket.OPEN) {
client.send(`Hola, recib&#237; tu mensaje de WebSocket: ${message}`);
}
});
});
// Register diconect
ws.on(&#39;close&#39;, () =&gt; {
console.log(&#39;Cliente WebSocket desconectado&#39;);
});
});
// Socket.io connections:
io.on(&#39;connection&#39;, (socket) =&gt; {
console.log(&#39;Nuevo cliente Socket.io conectado&#39;);
socket.on(&#39;message&#39;, (message) =&gt; {
console.log(`Recibido mensaje de Socket.io: ${message}`);
io.emit(&#39;message&#39;, `Hola, recib&#237; tu mensaje de Socket.io: ${message}`);
});
// Register diconect
socket.on(&#39;disconnect&#39;, () =&gt; {
console.log(&#39;Cliente Socket.io desconectado&#39;);
});
});
// Launch Express server on 3000
expresServer.listen(3000, () =&gt; {
console.log(&#39;Express server listening on 3000&#39;);
});

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 &quot;Poco/Net/HTTPRequest.h&quot;
#include &quot;Poco/Net/HTTPResponse.h&quot;
#include &quot;Poco/Net/HTTPMessage.h&quot;
#include &quot;Poco/Net/WebSocket.h&quot;
#include &quot;Poco/Net/HTTPClientSession.h&quot;
#include &lt;iostream&gt;
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(&quot;192.168.50.122&quot;,4000);
HTTPRequest request(HTTPRequest::HTTP_GET, &quot;/?encoding=text&quot;,HTTPMessage::HTTP_1_1);
request.set(&quot;origin&quot;, &quot;Cliente&quot;);
HTTPResponse response;
try {
WebSocket* m_psock = new WebSocket(cs, request, response);
std::string text = &quot;Hello, world!&quot;;
auto len = m_psock-&gt;sendFrame(text.c_str(), text.length(), WebSocket::FRAME_TEXT);
int flags=0;
char receiveBuff[256];
int rlen=m_psock-&gt;receiveFrame(receiveBuff,256,flags);
std::cout &lt;&lt; receiveBuff &lt;&lt; std::endl;
m_psock-&gt;close();
delete m_psock;
} catch (std::exception &amp;e) {
std::cout &lt;&lt; &quot;Exception &quot; &lt;&lt; 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 &quot;http&quot;;
import { Server } from &quot;socket.io&quot;;
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) =&gt; {
socket.on(&quot;connection&quot;, (clientSocket) =&gt; {
// ...
});
});
server.listen(3000, () =&gt; console.log(&quot;listening on port 3000&quot;));
server1.listen(4000, () =&gt; console.log(&quot;listening on port 4000&quot;));

This was a try, so you can rename all variables for better programming experience.

For import to work, you need to add &quot;type&quot;: &quot;module&quot;, to package.json, or convert to commonjs/require.

答案2

得分: 0

你可以创建多个服务器,每个服务器监听不同的端口。

英文:

You can create multiple servers and each listen on different ports.

huangapple
  • 本文由 发表于 2023年6月22日 00:15:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525282.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定