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

6ovsh4lw  于 2023-06-22  发布在  Node.js
关注(0)|答案(2)|浏览(171)

我想创建一个服务器,监听来自标准websockets和www.example.com websockets的连接socket.io。另外,我可以让它们只在3000端口上工作,但如果两者都在该端口上侦听,那么它就不工作了,标准的websockets抛出了很多错误,所以我试图让它们在不同的端口上侦听,socket.io(使用express服务器)在端口3000上,标准的websockets在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');
});

但是当我尝试用POCO C连接到标准的websockets时,它现在给出了一个Net Exception。我只是改变了端口,所以我不知道为什么它不工作。我从来没有打开过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 << "Exception " << e.what();
    }
}
b4lqfgs4

b4lqfgs41#

您可以创建多个服务器,每个服务器在不同的端口上侦听。

yx2lnoni

yx2lnoni2#

我是这样做的:

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"));

这是一个尝试,因此您可以重命名所有变量以获得更好的编程体验。
要使import工作,您需要将"type": "module",添加到package.json,或转换为commonjs/require。

相关问题