Socket.io as a client

is there any way to run socketio as a client (not a browser, but a nodejs script)

I need to stream data from the server to some clients (browsers) and to another linux machine (only to run nodejs to get variables, without a browser)

Any ideas are welcome

Hi

+7
source share
4 answers

There is a github project that implements the socket.io client. Look at here:

https://github.com/remy/Socket.io-node-client

var socket = new io.Socket('localhost', 8000); socket.on('connect', function () { console.log('yay, connected!'); socket.send('hi there!'); }); socket.on('message', function (msg) { console.log('a new message came in: ' + JSON.stringify(msg)); }); socket.connect(); 
+4
source

I believe you can just use socket.io-client. require this and use it in your node.js code, as in the client / browser. I also found this interesting tutorial right now => http://liamkaufman.com/blog/2012/01/28/testing-socketio-with-mocha-should-and-socketio-client/

+3
source

Just require('socket.io-client') and run $ node client.js as pointed out by Alfred . I confirm that this works with socket.io-client v1.4.8. To demonstrate, see the following code:

 // client.js var io = require('socket.io-client'); var socket = io('http://localhost:3000/'); socket.on('connect', function () { socket.emit('echo', {msg: 'Hello universe!'}, function (response) { console.log(response.msg); socket.disconnect(); // otherwise the node process keeps on running. }); }); 

Server:

 // server.js var io = require('socket.io')(3000); io.on('connection', function (socket) { socket.on('echo', function (data, response) { response(data); }); }); 

Unscrew the server using $ node server.js and then the $ node client.js in another terminal and see how the magic happens:

 $ node client.js Hello universe! 

It works! A very convenient way, for example, is to check your socket.io API.

+1
source

In this case, use the http request.

 var port=3000; //original port var bridge = express.createServer( express.logger() , express.bodyParser() ); bridge.post('/msg', function(req, res){ res.writeHead(200,{'Content-Type':'text/plain'}); //res.write(req.params.msg); res.end(req.params.msg); console.log(); io.sockets.in().emit('message', "chat", req.body.user_id,req.body.msg); //SEND! }); bridge.listen(parseInt(port)+1,function() { var addr = bridge.address(); console.log(' app listening on http://' + addr.address + ':' + addr.port); }); 

This is my code. good luck.

0
source

All Articles