用于 socket.io 服务器的 Node.js 客户端
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10703513/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js client for a socket.io server
提问by Predrag Stojadinovi?
I have a socket.io server running and a matching webpage with a socket.io.js client. All works fine.
我有一个正在运行的 socket.io 服务器和一个带有 socket.io.js 客户端的匹配网页。一切正常。
But, I am wondering if it is possible, on another machine, to run a separate node.js application which would act as a client and connect to the mentioned socket.io server?
但是,我想知道是否有可能在另一台机器上运行一个单独的 node.js 应用程序,作为客户端并连接到提到的 socket.io 服务器?
采纳答案by alessioalex
That should be possible using Socket.IO-client: https://github.com/LearnBoost/socket.io-client
这应该可以使用 Socket.IO-client: https://github.com/LearnBoost/socket.io-client
回答by AzizSM
Adding in example for solution given earlier. By using socket.io-clienthttps://github.com/socketio/socket.io-client
添加之前给出的解决方案的示例。通过使用socket.io-clienthttps://github.com/socketio/socket.io-client
Client Side:
客户端:
//client.js
var io = require('socket.io-client');
var socket = io.connect('http://localhost:3000', {reconnect: true});
// Add a connect listener
socket.on('connect', function (socket) {
console.log('Connected!');
});
socket.emit('CH01', 'me', 'test msg');
Server Side :
服务器端 :
//server.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function (socket){
console.log('connection');
socket.on('CH01', function (from, msg) {
console.log('MSG', from, ' saying ', msg);
});
});
http.listen(3000, function () {
console.log('listening on *:3000');
});
Run :
跑 :
Open 2 console and run node server.jsand node client.js
打开 2 控制台并运行node server.js和node client.js
回答by Predrag Stojadinovi?
After installing socket.io-client:
安装 socket.io-client 后:
npm install socket.io-client
This is how the client code looks like:
这是客户端代码的样子:
var io = require('socket.io-client'),
socket = io.connect('localhost', {
port: 1337
});
socket.on('connect', function () { console.log("socket connected"); });
socket.emit('private message', { user: 'me', msg: 'whazzzup?' });
Thanks alessioalex.
谢谢alessioalex。
回答by Suleman Tanveer
Yes you can use any client as long as it is supported by socket.io. No matter whether its node, java, android or swift. All you have to do is install the client package of socket.io.
是的,只要 socket.io 支持,您就可以使用任何客户端。无论是 node、java、android 还是 swift。您所要做的就是安装 socket.io 的客户端包。

