简体   繁体   English

Socket.io客户端简单客户端/服务器测试无法连接-Node.js

[英]Socket.io-client simple client/server test wont connect - Node.js

I am trying to get some simple communication to work in Node.js using socket.io and socket.io-client. 我正在尝试使用socket.io和socket.io-client在Node.js中进行一些简单的通信。

I have two scripts, server.js and client.js. 我有两个脚本,server.js和client.js。

The server.js script can bind to a webfacing port and act like a normal server/socket.io host, which all works when used with the browser client, server.js脚本可以绑定到网络端口,并像普通的server / socket.io主机一样工作,当与浏览器客户端一起使用时,它们都可以工作,

but the client.js (running in another node script) doesn't work, it just waits not outputting anything. 但是client.js(在另一个节点脚本中运行)不起作用,只是等待不输出任何内容。 I expect my socket.io-client in client.js to connect to the socket.io instance in server.js and for both to display a message in their console to say they're connected. 我希望client.js中的socket.io-client连接到server.js中的socket.io实例,并且两者都在其控制台中显示一条消息以表明已连接。

server.js code: server.js代码:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
    console.log("\nNew server request: "+req.url+"\n");

    // sends a html file with a script that connects
    // to socket.io running in server.js
    res.sendFile(__dirname+'/webroot/index.html');
});

// listens for connections
io.on('connect', function(socket){
  console.log('a client connected');
});

// start listening on server
http.listen(9000, function(){
  console.log('listening: 9000');
});

client.js code: client.js代码:

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

// connect to server.js socket
var socket = io('http://hostsite.com', {
    port: 9000
});

socket.on('connect', function(){
    console.log("connected\n");
});

installed with npm 用npm安装

npm install socket.io // version: 1.0.6
npm install socket.io-client // version: 1.0.6
npm install express // version: 4.8.5

Ideally I don't want to be using express or an http server, just a socket communication between two Node.js scripts, one on a server machine, one on a client machine. 理想情况下,我不想使用Express或http服务器,而只是两个Node.js脚本之间的套接字通信,一个在服务器计算机上,一个在客户端计算机上。

Thanks for any help :) 谢谢你的帮助 :)

For some reason, it wouldn't connect when i used: 由于某种原因,当我使用它时它不会连接:

npm install socket.io-client

and

require('socket.io-client');

But it does connect if I use the client that comes with the main package 但是如果我使用主软件包附带的客户端,它确实可以连接

npm install socket.io

and

require('socket.io/node_modules/socket.io-client');

Took a while to figure out, but hopefully now it will take someone else less time; 花了一点时间来弄清楚,但希望现在这将花费别人更少的时间。 if they face the same problem. 如果他们面临同样的问题。

你有没有尝试过:

var socket = io.connect('http://hostsite.com:9000');

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

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