我有一个正在运行的socket.io服务器和一个匹配的包含socket.io.js客户端的网页。一切正常。
但是,我想知道是否可能在另一台机器上运行一个单独的node.js应用程序,作为客户端连接到所提到的socket.io服务器?
但是,我想知道是否可能在另一台机器上运行一个单独的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
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?' });
。.emit()
之前查看socket.connected
属性时,它是false
。 - ekkisconst io = require('socket.io-client');
const socket_url = "http://localhost:8081";
let socket = io.connect(socket_url);
socket.on('connect', function () {
socket.emit("event_name", {});
});
是的,只要它被socket.io支持,您可以使用任何客户端,无论是node、java、android还是swift。您所需要做的就是安装socket.io的客户端包。
类似这样的方法对我有用
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);
});
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);
});
io.connect
函数,它将无法正常工作。正确的调用方式是:socket = io.connect('http://localhost:1337');
请注意不要改变原意,并使翻译更加通俗易懂。 - ceremcem