I am trying to communicate server-client communication using TCP-IP in node js
Below is my server side code and I have a GSM device which acts as a client.When GSM device connects to the server I get the message that device is connected! but when I cut off the power supply of GSM device then the server should recognize that device is disconnected but no any message displays on screen even if I have code for the disconnect event.
server code
// Load the TCP Library
net = require('net');
// Keep track of the chat clients
var clients = [];
// Start a TCP Server
net.createServer(function (socket) {
// Identify this client
socket.name = socket.remoteAddress + ":" + socket.remotePort
// Put this new client in the list
clients.push(socket);
// Send a nice welcome message and announce
socket.write("Welcome " + socket.name + "\n");
broadcast(socket.name + " Device is connected!\n", socket);
// Handle incoming messages from clients.
socket.on('data', function (data) {
broadcast(socket.name + "> " + data, socket);
});
// Remove the client from the list when it leaves
socket.on('end', function () {
clients.splice(clients.indexOf(socket), 1);
broadcast(socket.name + " Device left.\n");
});
// Send a message to all clients
function broadcast(message, sender) {
clients.forEach(function (client) {
// Don't want to send it to sender
if (client === sender) return;
client.write(message);
});
// Log it to the server output too
process.stdout.write(message)
}
}).listen(5000);
// Put a friendly message on the terminal of the server.
console.log("Chat server running at port 5000\n");
// Load the TCP Library
net = require('net');
// Keep track of the chat clients
var clients = [];
// Start a TCP Server
net.createServer(function(socket) {
try {
socket.setKeepAlive(true, 600); //1 min = 60000 milliseconds.
} catch (exception) {
console.log('exception', exception);
}
socket.on('error', onError.bind({}, socket));
function onError(socket) {
//console.log('Socket error!', socket);
console.log('name', socket.name);
}
// Identify this client
socket.name = socket.remoteAddress + ":" + socket.remotePort
// Put this new client in the list
clients.push(socket);
// Send a nice welcome message and announce
socket.write("Welcome " + socket.name + "\n");
broadcast(socket.name + " joined\n", socket);
// Handle incoming messages from clients.
socket.on('data', function(data) {
console.log(data);
broadcast(socket.name + "> " + data, socket);
});
// Remove the client from the list when it leaves
socket.on('end', function() {
clients.splice(clients.indexOf(socket), 1);
broadcast(socket.name + " left .\n");
});
// Send a message to all clients
function broadcast(message, sender) {
clients.forEach(function(client) {
// Don't want to send it to sender
if (client === sender) return;
client.write(message);
});
// Log it to the server output too
process.stdout.write(message)
}
}).listen(8003);
// Put a friendly message on the terminal of the server.
console.log("Chat server running at port 8003\n");
Related
When I run this code, I am able to send the message successfully to the broadcast address but there is no output on the message event listener. Same code is working on macOS but not on ubuntu 16.04. I am using node v6.11.1.
var dgram = require('dgram');
var socket = dgram.createSocket('udp4');
var testMessage = "[hello world] pid: " + process.pid;
var broadcastAddress = '255.255.255.255';
var broadcastPort = 5555;
socket.bind(broadcastPort, '0.0.0.0', function(){
socket.setBroadcast(true);
});
socket.on("message", function ( data, rinfo ) {
console.log("Message received from ", rinfo.address, " : ", data.toString());
});
setInterval(function () {
socket.send(new Buffer(testMessage),
0,
testMessage.length,
broadcastPort,
broadcastAddress,
function (err) {
if (err) console.log(err);
console.log("Message sent");
}
);
}, 1000);
After wasting a lot of precious time, I found out that my firewall was restricting the incoming udp package.
I am working on an IoT project. With nodejs on heroku, i have created a server on heroku. Then my IoT device will try to establish a connection. But when i tried it, the connection automatically closes. Below is the script i am using. It is working locally.
net = require('net');
var clients = [];
net.createServer(function (socket) {
socket.name = socket.remoteAddress + ":" + socket.remotePort
clients.push(socket);
broadcast(socket.name + " joined the chat\n", socket);
socket.on('data', function (data) {
broadcast(socket.name + "> " + data, socket);
});
socket.on('end', function () {
clients.splice(clients.indexOf(socket), 1);
broadcast(socket.name + " left the chat.\n");
});
function broadcast(message, sender) {
clients.forEach(function (client) {
if (client === sender) return;
client.write(message);
});
process.stdout.write(message)
}
}).listen(process.env.PORT || 8899);
console.log("Chat server running at port 8899\n");
Please help.
I am also facing the same problem but I think the problem might be this
According to this article
If no data is received from the dyno within the 55 second window the
connection is terminated and an H15 error is logged.
Similarly, if no data is received from the client within the 55 second
window the connection is terminated an an H28 error is logged.
Good day
I need to connect a lot of pc's to a main server, through a server of units
I have something but I don't have all complete
Main Server
socketIo = require("socket.io"),
ioServer = socketIo(server),
ioServer.sockets.on("connection",function(socket){
// Display a connected message
console.log("Server-Client Connected!");
// When we receive a message...
socket.on("message",function(data){
// We got a message... I dunno what we should do with this...
console.log(data);
console.log(data.from + " is connected with ip " + data.ip);
socket.emit('message', { 'from': '10.19.17.101', 'answer':'I already added you '+data.from });
});
});
Server Units
socketIo = require("socket.io"),
ioServer = socketIo(server),
ioClient = require("socket.io-client")('http://10.19.17.101:7700')
ioClient.on('connect', function(){
ioClient.on('message',function(data){
console.log(data.from + " answered: " + data.answer);
ioServer.to('pxe4').emit('message',data);
});
ioClient.emit('message',{ 'from': 'pxe4', 'ip':'10.19.16.84' });
});
ioServer.sockets.on("connection",function(socket){
// Display a connected message
console.log("User-Client Connected!");
// When we receive a message...
socket.on("message",function(data){
// We got a message... I dunno what we should do with this...
console.log(data);
console.log(data.from + " is connected with ip " + data.ip);
socket.emit('message', { 'from': '10.19.16.84', 'answer':'I already added you '+data.from });
ioClient.emit("message",data);
});
socket.on("disconnect",function(data){
// We need to notify Server 2 that the client has disconnected
ioClient.emit("message","UD,"+socket.id);
// Other logic you may or may not want
// Your other disconnect code here
});
});
Units
ioClient = require("socket.io-client")('http://10.19.16.84:7770'),
ioClient.on('connect', function(){
ioClient.on('message',function(data){
// We received a message from Server 2
// We are going to forward/broadcast that message to the "Lobby" room
console.log(data.from + " answered: " + data.answer);
});
ioClient.emit('message',forsend);
});
I was wondering if at this moment I can send some information from Main Server to a specific unit?
If someone could help me, I will be thankful.
When connecting from each client on the main server or Server Units you recive a socket object which contains socketid. You have to save those socket id's in some data storge for speedy access with the server information. When you have to emit data to specific socket you have to query that specific socket from data storage and emit the data. On disconnect you have to pull that particular socket from data storage
In node, when you create a socket server and connect to it with a client, the write function triggers the data event, but it seems there is no way to distinguish the source of the traffic (other than adding your own IDs/headers to each sent buffer).
For example, this is the output "server says hello" from the server.write, and then all of the "n client msg" are from client.write, and they all come out in on('data', fn):
➜ sockets node client.js
client connected to server!
client data: server says hello
client data: 1 client msg!
client data: 2 client msg!
client data: 3 client msg!
client data: 4 client msg!
Is there a correct way to distinguish the source of the data on a socket?
The code for a simple client:
// client.js
var net = require('net');
var split = require('split');
var client = net.connect({
port: 8124
}, function() {
//'connect' listener
console.log('client connected to server!');
client.write('1 client msg!\r\n');
client.write('2 client msg!\r\n');
client.write('3 client msg!\r\n');
client.write('4 client msg!\r\n');
});
client.on('end', function() {
console.log('client disconnected from server');
});
var stream = client.pipe(split());
stream.on('data', function(data) {
console.log("client data: " + data.toString());
});
and the code for the server
// server.js
var net = require('net');
var split = require('split');
var server = net.createServer(function(c) { //'connection' listener
console.log('client connected');
c.on('end', function() {
console.log('client disconnected');
});
c.write('server says hello\r\n');
c.pipe(c);
var stream = c.pipe(split());
stream.on('data', function(data) {
console.log("client data: " + data.toString());
});
});
server.listen(8124, function() { //'listening' listener
console.log('server bound');
});
The source of the traffic is the server.
If you're wanting to know whether it's data being echoed back to the client by the server, you will have to come up with your own protocol for denoting that.
For example, the server could respond with newline-delimited JSON data that is prefixed by a special byte that indicates whether it's an echo or an "original" response (or any other kind of "type" value you want to have). Then the client reads a line in, checks the first byte value to know if it's an echo or not, then JSON.parse()s the rest of the line after the first byte.
You can distinguish each client with:
c.name = c.remoteAddress + ":" + c.remotePort;
c.on('data', function(data) {
console.log('data ' + data + ' from ' + c.name);
});
Below is the websocket server side code that uses "ws" plugin.
var WebSocketServer = require('ws').Server
,wsSend = new WebSocketServer({port: 8080}) //Client sends message on this port.
,wsReceive = new WebSocketServer({port: 8081}) //Response is sent on this port.
,clientMessage;
wsSend.on('connection', ReceiveSocketConnection);//From client.
//Callback function on connection with client.
function ReceiveSocketConnection(webSocket) {
webSocket.on('message', GetMessageFromClient);
}
//Handler to receive message from client.
function GetMessageFromClient(messageFromClient) {
clientMessage = messageFromClient; //Message from client saved into variable
}
wsReceive.on('connection', SendSocketConnection);//To client.
function SendSocketConnection(webSocket) {
webSocket.send(clientMessage);//Here clientMessage is undefined
}
Below is the client side code.
var WebSocket = require('ws')
, wsSend = new WebSocket('ws://localhost:8080') //send port
, wsReceive = new WebSocket('ws://localhost:8081'); //receive port
//Open connection on send port.
wsSend.on('open', function() {
wsSend.send('Hi I am new to websockets');
});
//Open connection on receive port.
wsReceive.on('open', function() {
//Do nothing
});
//Receive message from server via port 8081
wsReceive.on('message', function(message) {
console.log('received: %s', message);
});
Separate ports for sending and receiving messages are there because it is a design decision.
I want to echo the message by receiving it on one port and sending it on another.
Problem : The message from the client is not saved into the local variable(i.e clientMessage).Any suggestions?
this should work, however i recommend using http://socket.io/
var WebSocketServer = require('ws').Server
,wsSend = new WebSocketServer({port: 8080}) //Client sends message on this port.
,wsReceive = new WebSocketServer({port: 8081}) //Response is sent on this port.
wsReceive.broadcast = function(data) {
for(var i in this.clients)
this.clients[i].send(data);
};
wsSend.on('connection', function(ws) {
ws.on('message', function(message) {
console.log('received: %s', message);
try {
console.log('sending: %s', message);
wsReceive.broadcast(message);
} catch (e) {
console.log(e);
}
});
});