Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save GuillermoPena/19cac60aaee9379fd753 to your computer and use it in GitHub Desktop.
Save GuillermoPena/19cac60aaee9379fd753 to your computer and use it in GitHub Desktop.
NodeJS - SOCKET.IO : Managing websockets
// Managing websocket with socket.io
// Setting a web socket and sending a message from client to server.
// Server side
var app = require('express')()
, util = require('util')
, server = require('http').createServer(app)
, io = require('socket.io').listen(server)
, port = 8013
server.listen(port)
io.set("heartbeat interval", 10)
io.set("close timeout", 12)
io.sockets.on('connection', function (socket) {
var id = socket.id
var endpoint = socket.handshake.address
var client = 'unknown'
console.log("Id: " + id + " - Endpoint: " + endpoint.address + ":" + endpoint.port)
socket.on('disconnect', function () {
console.log(client, ' - Client disconnected')
})
socket.on('message', function (message) {
client = message.from
console.log(message.from, 'said', message.content)
})
socket.on('ping', function (from) {
client = from
console.log('Ping from client ' + client)
socket.emit('pong')
})
})
// **********************************************************************************//
// Client side
// Sintaxis: node socket.io.client.js [client name]
var io = require('socket.io/node_modules/socket.io-client')
var util = require('util')
var message = { 'from': process.argv[2], 'content': 'Hello world!'}
var socket = io.connect( 'localhost'
, { 'port':8013
, 'connect timeout': 10000
, 'try multiple transports': false
, 'reconnect': true
, 'reconnection delay': 200
, 'max reconnection attempts': 5
}
)
socket.on('connect', function(){
socket.on('pong', function(){
console.log('Pong!')
console.log('Sending message: ' + message.content)
socket.json.send(message)
socket.disconnect()
})
socket.on('disconnect', function(){
console.log('Disconnected!')
})
console.log("Ping... ")
socket.emit('ping', message.from)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment