Js 客户端,用于 socket.io 服务器

我运行了一个 socket.io 服务器和一个带有 socket.io.js 客户端的匹配网页。

但是,我想知道是否有可能在另一台机器上运行一个单独的 node.js 应用程序,该应用程序将充当客户机并连接到上面提到的 socket.io 服务器?

133008 次浏览

使用 Socket.IO-client: https://github.com/LearnBoost/socket.io-client应该可以做到这一点

安装 socket.io-client 之后:

npm install socket.io-client

这就是客户机代码的样子:

var io = require('socket.io-client'),
socket = io.connect('http://localhost', {
port: 1337,
reconnect: true
});
socket.on('connect', function () { console.log("socket connected"); });
socket.emit('private message', { user: 'me', msg: 'whazzzup?' });

谢谢 Alessioalex

通过使用 socket.io-client https://github.com/socketio/socket.io-client为前面给出的解决方案添加示例

客户端:

//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.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');
});

跑步:

打开2控制台并运行 node server.jsnode client.js

是的,您可以使用任何客户端,只要它是由 socket.io 支持的。无论是它的节点,java,android 或迅捷。您所要做的就是安装 socket.io 的客户端包。

客户端代码: 我有一个要求,我的 nodejs 网络服务器应该既作为服务器,也作为客户端,所以我添加了以下代码,当我需要它作为客户端,它应该工作良好,我正在使用它,并为我工作良好!

const socket = require('socket.io-client')('http://192.168.0.8:5000', {
reconnection: true,
reconnectionDelay: 10000
});
    

socket.on('connect', (data) => {
console.log('Connected to Socket');
});
        

socket.on('event_name', (data) => {
console.log("-----------------received event data from the socket io server");
});
    

//either 'io server disconnect' or 'io client disconnect'
socket.on('disconnect', (reason) => {
console.log("client disconnected");
if (reason === 'io server disconnect') {
// the disconnection was initiated by the server, you need to reconnect manually
console.log("server disconnected the client, trying to reconnect");
socket.connect();
}else{
console.log("trying to reconnect again with server");
}
// else the socket will automatically try to reconnect
});
    

socket.on('error', (error) => {
console.log(error);
});

这样的方法对我很有效

const WebSocket = require('ws');
const ccStreamer = new WebSocket('wss://somthing.com');


ccStreamer.on('open', function open() {
var subRequest = {
"action": "SubAdd",
"subs": [""]
};
ccStreamer.send(JSON.stringify(subRequest));
});


ccStreamer.on('message', function incoming(data) {
console.log(data);
});