I have implemented socket.io with node.js http server. The server pushes the Realtime data to the clients. I noticed a problem that when the server is restarted the client does not get data automatically means it does not reconnect automatically with the server. Please suggest the solution. My client code is as below
client index.html
<script>
var socket = io.connect('http://localhost');
socket.on('field', function (data) {
console.log(data); });
</script>
server.js
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(8070);
var mysocket = 0;
function handler(req, res)
{
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
console.log('index.html connected');
mysocket = socket;
});
//udp server on 41181
var dgram = require("dgram");
var server = dgram.createSocket("udp4");
server.on("message", function (msg, rinfo) {
console.log("msg: " + msg);
if (mysocket != 0){
mysocket.emit('field', "" + msg);
}
});
server.on("listening", function () {
var address = server.address();
console.log("udp server listening " + address.address + ":" +
address.port);
});
server.bind(41181);
Related
I am making a real-time Lumen API. For that i have used Node.js to create the server.
It works perfectly fine on localhost, but not when published
This is the code for my Node Server.js
var app = require('http').createServer(handler);
var io = require('socket.io')(app);
var Redis = require('ioredis');
var redis = new Redis();
app.listen(6001, function() {
console.log('Server chalu hua');
});
function handler(req, res) {
res.writeHead(200);
res.end('');
}
io.on('connection', function(socket) {
console.log('Lijiye Nya connection bna diya gya');
});
io.on('disconnect', function(socket) {
console.log('Connection Dropped');
});
redis.psubscribe('*', function(err, count) {
//
});
redis.on('pmessage', function(subscribed, channel, message) {
console.log(channel);
message = JSON.parse(message);
console.log(message);
io.emit(channel, message.data);
})
Can someone tell what to do, to make it work in Production
When no room is specified client receive the message but when specify a room I am unable to receive message on client.
server.js
var socket = require('socket.io');
var mysql = require('mysql');
const path = require('path');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen(server);
var port = PORT;
io.on('connection', (socket) => {
console.log('new connection made');
socket.on('subscribe', function (room) {
socket.room = room;
socket.join(socket.room, function () {
console.log('joined:' + room); // outputs joined: 1
socket.on('send-message', (data) => {
io.to(data.room).emit('message-received', data.message);
console.log("sent to room:" + data.room); // outputs sent to room: 1
});
});
});
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
});
client.js
this.socket = io.connect('ws://IP:PORT');
this.socket.on('connect', () => {
console.log("connection made"); // it output connection made in console
this.socket.emit('subscribe', 1);
});
this.socket.on('message-received', (message: any) => {
console.log(message);
});
on server.js I have tried several options below but still unable to emit 'message-received' on client side:
// io.emit('message-received', data);
// io.to(data.room).emit('message-received', {
// room: data.room,
// message: data.message
// });
// io.sockets.in(data.room).emit('message-received', {
// room: data.room,
// message: data.message
// });
//io.broadcast.to(data.room).emit('message-received', data.message);
using latest socket.io library with angular 4
based on what i see on your clientside and serverSide code, I believe the problem is in the clientSide code...
On your server, inside the 'subscribe' event the server is also listening for 'send-message' event, which you're never emiting from the client side!!
Therefore, if you emit 'send-message' event with data(this should include message) as parameter, only then the server would emit 'message-received' event to the client..
HOPE THIS HELPS!
I have a node WebServer capable of communicating with Browser(say browserInstance) and linux terminal(say ProxyInstance) via Websockets. The job of the webserver is to handover the data from terminal to WebBrowser and vice-verse. Please find the server.js code below:
var express = require('express');
var expressWs = require('express-ws');
var expressWs = expressWs(express());
var app = expressWs.app;
var appForpage = express();
var browserInstance;
var ProxyInstance;
var browserCounter = 0;
var ProxyCounter = 0;
app.ws('/fromBrowser', function(ws, req, next) {
console.log("~~~~~~~~~~~~BROWSER");
if(browserCounter == 1){
ws.on('message', function(msg) {
console.log("Messagae from Browser :", msg);
ProxyInstance.send(msg);
});
}else{
browserInstance = ws;
ws.on('message', function(msg) {
console.log("Message from Browser :", msg);
ProxyInstance.send(msg);
});
browserCounter = 1;
}
ws.on('close', function(){
console.log("Ws Connection closed");
});
//next();
});
app.ws('/fromProxy', function(ws, req, next) {
console.log("~~~~~~~~~~~~PROXY");
if(ProxyCounter == 0){
ProxyInstance = ws;
ProxyCounter = 1;
}else if(browserCounter == 1){
ws.on('message', function(msg) {
console.log("Message from Proxy: ", msg);
browserInstance.send(msg);
});
}
ws.on('close', function(){
console.log("Ws Connection closed");
});
//next();
});
appForpage.use(express.static(__dirname + '/public/')); // index.html resides in public directory
appForpage.listen(5000)
app.listen(3000)
First I am creating ws connection from proxy to webserver(/fromProxy) and then from browser(/fromBrowser). The connection was successfully created. When i try to send data from Browser to proxy via Webserver, it works fine. In return to the 1st message at proxy end when tries to communicate Browser via WebServer, this one failed. I haven't received any message from Proxy. I need to run the respective ends in the same order(Proxy first and then Browser..).
I am just beginner to node. I haven't find any example over internet for my case. What am I missing here ?
That's really silly :( .I haven't registered my messsage callback from proxy. Please find the working code below.
var express = require('express');
var expressWs = require('express-ws');
var expressWs = expressWs(express());
var app = expressWs.app;
var appForpage = express();
var browserInstance;
var ProxyInstance;
var browserCounter = 0;
var ProxyCounter = 0;
app.ws('/fromBrowser', function(ws, req, next) {
console.log("~~~~~~~~~~~~BROWSER");
if(browserCounter == 1){
ws.on('message', function(msg) {
console.log("Messagae from Browser :", msg);
ProxyInstance.send(msg);
});
}else{
browserInstance = ws;
ws.on('message', function(msg) {
console.log("Message from Browser :", msg);
ProxyInstance.send(msg);
});
browserCounter = 1;
}
ws.on('close', function(){
console.log("Ws Connection closed");
});
//next();
});
app.ws('/fromProxy', function(ws, req, next) {
console.log("~~~~~~~~~~~~PROXY");
if(ProxyCounter == 0){
ProxyInstance = ws;
ProxyCounter = 1;
}
/*This is the place where i went wrong. damnn..*/
ws.on('message', function(msg) {
console.log("Message from Proxy: ", msg);
browserInstance.send(msg);
});
ws.on('close', function(){
console.log("Ws Connection closed");
});
//next();
});
appForpage.use(express.static(__dirname + '/public/')); // index.html resides in public directory
appForpage.listen(5000)
app.listen(3000)
created index.js (server)
var express = require('express');
var app = express();
///creating server
var server = require('http').createServer(app);
var io = require('socket.io').listen(server, { origins:'http://nodejs-atnodejs.rhcloud.com:8000' });
below is remaining code
Routing to index.html page
app.get('/', function (req, res) {
console.log('in socket---' + res);
res.sendfile('index.html');
});
///socket connection
io.sockets.on('connection', function (socket) {
socket.on('chatmessage', function (msg) {
io.emit('chatmessage', msg);
console.log('in socket---' + data);
});
});
/// Listen to Openshift port
server.listen(process.env.OPENSHIFT_NODEJS_PORT, process.env.OPENSHIFT_NODEJS_IP);
created index.html(client)
src="http://nodejs-atnodejs.rhcloud.com:8000/socket.io/socket.io.js
var socket = io.connect('http://nodejs-atnodejs.rhcloud.com:8000');
console.log('this is index page');
socket.on('chatmessage', function (data) {
console.log('chatmessage---' + data);
socket.emit('chatmessage', { my: 'data' });
});
When accessed from browser:
Problem is not getting "console.log('chatmessage---' + data);" which is inside the socket..
and keep on getting xhr-polling../t=xxxxx responses..
is my socket working properly?
Both your browser and server code is listening for an event of 'chatmessage' after connection either your browser or server should be emitting the event first and than the other should be listening such as...
// server
io.sockets.on('connection', function (socket) {
socket.emit('chatmessage', /*some data*/);
});
//client
socket.on('chatmessage', function (data) {
console.log('chatmessage---' + data);
});
Using socket.io and nodeJS cluster, looks like Websocket protocol fails and it falls back to long polling, any idea why it isnt using websocket?
This is the only error in console
WebSocket connection to
'ws://localhost:5050/socket.io/?EIO=3&transport=websocket&sid=82qh7nBXGusxyelJAAAG'
failed: Connection closed before receiving a handshake response
Here is my node application
if (cluster.isMaster) {
// we create a HTTP server, but we do not use listen
// that way, we have a socket.io server that doesn't accept connections
var server = require('http').createServer();
var io = require('socket.io').listen(server);
var redis = require('socket.io-redis');
var fs = require('fs');
io.adapter(redis({host: '127.0.0.1', port: 6379}));
var i = 0;
setInterval(function () {
// all workers will receive this in Redis, and emit
io.sockets.in('EURUSD').emit('message', 'EURUSD ' + i++);
io.sockets.in('GBPUSD').emit('message', 'GBPUSD ' + i++);
}, 1000);
for (var i = 0; i < os.cpus().length; i++) {
cluster.fork();
}
cluster.on('online', function (worker) {
console.log("New Worker with ID ", worker.id);
});
cluster.on('exit', function (worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
}
if (cluster.isWorker) {
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(config.port);
var io = require('socket.io').listen(server);
var redis = require('socket.io-redis');
io.adapter(redis({host: '127.0.0.1', port: 6379}));
io.sockets.on('connection', function (socket) {
console.log('connected to worker id ', cluster.worker.id);
socket.on('join', function (room) {
socket.join(room);
});
});
app.get("/", function (req, res) {
res.sendFile('views/index.html', {root: __dirname});
});
}
Client code
var socket = io();
socket.on('message', function (data) {
var item = $('<li>' + data + '</li>');
$('ul').prepend(item);
});
socket.emit("join", "GBPUSD");
For those who may face similar issue, it turned out that I have the following line twice
var io = require('socket.io')(server);
Removing one, solved the issue.