提问者:小点点

Socket.io服务器未在网络外部工作


嗨!!!

在这个工具的帮助下,我设法将3000端口转发。https://www.yougetsignal.com/tools/open-ports/

我之所以转发这个端口,是因为我有一个聊天应用程序,我做的它在本地主机上运行得非常好。可悲的是,当我让我的朋友打开我的web聊天应用程序(http://mywebsite.com:81/chat/)时,javascript并没有通过3000端口连接到我的服务器上。。。

下面是我的一些代码:

server.js

const io = require('socket.io')(3000)

const users = {}

io.on('connection', socket => {
    // On message receive
    socket.on('msg', message => {
        //broadcast message
        socket.broadcast.emit('msg', {name: users[socket.id], msg: message});

        // If message starts with "/" AKA is a command
        if(message.startsWith("/")){
            message=message.split(" ");
            //message[0]= /help

            if(message[0] == "/say"){
                txt=message.splice(1).join(" "); // GET TEXT AFTER /help
                socket.emit('msg', {name: "TomatoBot", msg: txt});
            }else if(message[0] == "/help"){
                txt=message.splice(1).join(" "); // GET TEXT AFTER /help
                socket.emit('msg', {name: "TomatoBot", msg: "help dialog"});
            }else if(message[0] == "/list"){
                socket.emit('msg', {name: "TomatoBot", msg: users[socket.id]+" connected users:\n"});
            }else{
                //no commands found, throw error
                socket.emit('msg', {name: "TomatoBot", msg: "@"+users[socket.id]+"\nUnknown command: "+message[0]+". Type /help for a list of commands."});
            }
        }
    })

    // On user join
    socket.on('new', name => {
        users[socket.id] = name;
        socket.broadcast.emit('new', name);
    })

    // On user disconnect
    socket.on('disconnect', () => {
        socket.broadcast.emit('bye', users[socket.id]);
        delete users[socket.id];
    })
})

script.js(我的客户端脚本)

const socket = io(':3000'); // go from localhost:81 to localhost:3000!!
const form = document.getElementById('form');
const input = document.getElementById('input');
const msgbox = document.getElementById('msgbox');

const name = prompt('name?');
socket.emit('new', name);
appendMessage(name+' joined');
// etc etc.....

因此,正如我已经说过的,连接和消息在本地主机上通过,但只要我使用外部域/IP,就什么都不起作用了!!当从外部世界直接访问mywebsite.org:3000/socket.io/socket.io.js时,连接是有效的!!

我很迷路,一定是因为我的代码中有个愚蠢的错误。

谢谢大家的帮助!!


共1个答案

匿名用户

null

在服务器端

const http = require(`http`)
const io = require(`socket.io`)(http)

http.createServer(function (req, res) {
  // Use this server for http://mywebsite.com:81
}).listen(81)

io.on(`connection`, client => {
    // Use this socket for websocket
})

在客户端

const socket = io(`http://mywebsite.com:81`)