Node.js client for a socket.io server
Adding in example for solution given earlier. By using socket.io-client
https://github.com/socketio/socket.io-client
Client Side:
//client.jsvar io = require('socket.io-client');var socket = io.connect('http://localhost:3000', {reconnect: true});// Add a connect listenersocket.on('connect', function (socket) { console.log('Connected!');});socket.emit('CH01', 'me', 'test msg');
Server Side :
//server.jsvar 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');});
Run :
Open 2 console and run node server.js
and node client.js
After installing socket.io-client:
npm install socket.io-client
This is how the client code looks like:
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?' });
Thanks alessioalex.