socket.io as a client
Asked Answered
P

4

7

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

I need to broadcast data from a server to some clients (browsers) and to another linux machine (only running nodejs to get variables, no browser)

Any ideias is welcome

Regards

Pahang answered 28/1, 2012 at 2:33 Comment(1)
Looks like a duplicate of this question: #3843065Rounding
R
4

There is a project on github which implements a socket.io client. Take a look 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();
Rounding answered 28/1, 2012 at 3:8 Comment(0)
U
3

I believe you could just use socket.io-client. require that and use that in your node.js code as would 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/

Undershirt answered 30/1, 2012 at 6:53 Comment(0)
T
1

Just require('socket.io-client') and run $ node client.js as pointed out by Alfred. I confirm 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.
  });
});

The server:

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

Spin up the server with $ node server.js and then the client $ node client.js in another terminal and watch the magic happening:

$ node client.js
Hello universe!

It works! A very convenient way for example to test your socket.io API.

Tillis answered 29/9, 2016 at 12:54 Comment(0)
B
0

In that 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.

Bartizan answered 10/2, 2012 at 2:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.