我有一个正在运行的 socket.io 服务器和一个带有 socket.io.js 客户端的匹配网页。一切正常。
但是,我想知道是否有可能在另一台机器上运行一个单独的 node.js 应用程序,该应用程序将充当客户端并连接到提到的 socket.io 服务器?
这应该可以使用 Socket.IO-client:https ://github.com/LearnBoost/socket.io-client
添加前面给出的解决方案的示例。通过使用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.js
运行node client.js
安装 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 支持,您可以使用任何客户端。不管是node、java、android还是swift。你所要做的就是安装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);
});