简体   繁体   English

Nodejs socket.io客户端无法连接到Nodejs socket.io服务器

[英]Nodejs socket.io client cannot connect to Nodejs socket.io server

I use NodeJS both as the server and the client . 我使用NodeJS作为服务器客户端 (No web browsers) Server seems to be working, but client does not connect. (没有Web浏览器)服务器似乎正在工作,但客户端无法连接。 I tried to set the port in the options but it did not work. 我试图在选项中设置端口,但它不起作用。 I try to connect to the port 3000 over telnet and it connects to something, so the server is listening. 我尝试通过telnet连接到端口3000 ,它连接到某个东西,所以服务器正在监听。 What am I missing here? 我在这里错过了什么?

Server: 服务器:

var express = require('express');
var app = express();
var path = require('path');
var server = require('http').createServer(app);
var io = require('socket.io')();
var port = 3000;

server.listen(port,"127.0.0.1", () => {
    console.log('Server listening at port %d', port);
});

Client: 客户:

const io = require('socket.io-client');

const socket = io("http://127.0.0.1:3000",{reconnect:false});

socket.on('connect', function () {
    console.log('connected to the server');
});

As mentioned on the offical socket-io github page , you need to pass the http-server instance to the socket-io server: 正如在官方socket-io github页面上所提到的,您需要将http-server实例传递给socket-io服务器:

...
var server = require('http').createServer(app);
var io = require('socket.io')(server);
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM