在服务器和任意NodeJS进程之间创buildWeb套接字stream
在localhost:5000
上运行服务器,我想通过web套接字从另一个NodeJS进程连接到该服务器。
从我的networking套接字的经验,我总是需要服务器对象来创build一个Web套接字服务器。
var http = require('http'); // create http server var server = http.createServer(function(req, res) { // serve files and responses ... }); // Socket.io server listens to our app var io = require('socket.io').listen(server); // Send current time to all connected clients function sendTime() { io.sockets.emit('time', { time: new Date().toJSON() }); } // Send current time every 10 secs setInterval(sendTime, 10000); // Emit welcome message on connection io.sockets.on('connection', function(socket) { socket.emit('welcome', { message: 'Welcome!' }); socket.on('i am client', console.log); }); server.listen(3000);
这是一个使用socket.io
的小例子。 如果没有获得server
variables(因为这个服务器将部署在云中的某个地方),我怎样才能通过networking套接字连接到这台服务器?
一个丑陋的解决scheme将通过HTTP请求,但这不是networking套接字。 我想保持连接打开和pipe道数据在那里。
我怎样才能做到这一点?
你得到了socket.io-client
模块,把它require()
放到你的另一个nodejs服务器中,并使用你的另一个服务器(在这个例子中就是客户端)中的那个客户端模块,并从那个服务器连接到这个模块。
示例代码在这里: https : //github.com/automattic/socket.io-client
var socket = require('socket.io-client')('http://localhost'); socket.on('connect', function(){}); socket.on('event', function(data){}); socket.on('disconnect', function(){});