Socket IO event emission - javascript

I am trying to get a client to speak with a server and am unable to receive the events being emitted by the client. The connection is being established as the server console.logs connected to localhost:61201 whenever a client connects; but, there is no response from the clientEvents that are being emitted at intervals by the client.
server.js
const port = 61201;
const ipAddress = "127.0.0.1"
var http = require('http');
var io = require('socket.io');
var server = http.createServer();
server.listen(port, ipAddress);
var socket = io.listen(server);
socket.on('connect', () => {
console.log('connected to localhost:61201');
socket.on('clientEvent', function (data) {
console.log('message from the client:', data);
socket.emit('serverEvent', "thanks server! for sending '" + data + "'");
});
});
client.js
const port = 61201;
const ipAddress = "127.0.0.1";
const url = 'http://' + ipAddress + ':' + port;
var io = require('socket.io-client');
var socket = io(url);
socket.on('connect', () => {
socket.on('serverEvent', function (data) {
console.log('new message from the server:', data);
});
setInterval(function () {
socket.emit('clientEvent', Math.random());
console.log('message sent from the client');
}, 3000);
});

You need to use the socket object that the connect event returns. Try this
socket.on('connect', (clientSocket) => {
console.log('connected to localhost:61201');
clientSocket.on('clientEvent', function (data) {
console.log('message from the client:', data);
clientSocket.emit('serverEvent', "thanks server! for sending '" + data + "'");
});
});

Related

TCP socket server in node js with persistent connection

I have created one socket server in node js where I can send some data and receive from the server, but the problem is every time connection is closing and creating new PID for another request. here my requirement is once my IOT device connects to the server then the connection should stay there and I want to send, receive data any time.
Can anyone help me out?
I am posting my code below
Server code
var net = require('net');
// Create Server instance
var server = net.createServer(main);
server.listen(9010, function() {
console.log('server listening on %j', server.address());
});
function main(sock) {
sock.setEncoding("utf8");
sock.on('data', function(data) {
var data = data;
console.log('Request data is ', data);
console.log('Says:', data);
sock.write("responding to client");
sock.write(' exit');
});
sock.on('close', function () {
console.log('connection closed');
});
sock.on('error', function (err) {
console.log('Connection error: %s', err.message);
});
};
Client code
var net = require('net');
//params
var HOST = 'myhost';
var PORT = 9010;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('Hello socket server');
});
client.on('data', function(data) {
console.log('Recieved data: ' + data);
client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});

Connection closed before receiving a handshake response WebSocket

im trying to connect my client through web sockets in JS but I have this error
getUser.js:29 WebSocket connection to 'ws://localhost:8005/wsserver.js' failed: Connection closed before receiving a handshake response
But look my code:
getUser.js
var sock = new WebSocket("ws://localhost:8005/wsserver.js");
$('#data1').append("alors");
sock.onopen = function (event) {
$('#data').append("server status opened" + event.currentTarget.URL);
sock.send(JSON.stringify("coucou"));
console.log("sended");
};
sock.onmessage = function (event) {
$('#data').append(event.data);
console.log(event.data);
};
sock.onerror = function(error) {
console.log('WebSocket Error: ' + error);
};
And the server side code is:
wsserver.js
var WebSocketServer = require("ws").Server;
var ws = new WebSocketServer( { port: 8005 } );
console.log("Server started...");
ws.on('connection', function (ws) {
console.log("Browser connected online...")
ws.on("message", function (str) {
var ob = JSON.parse(str);
switch(ob.type) {
case 'text':
console.log("Received: " + ob.content)
ws.send('{ "type":"text", "content":"Server ready."}')
break;
case 'image':
console.log("Received: " + ob.content)
console.log("Here is an apricot...")
var path ="apricot.jpg";
var data = '{ "type":"image", "path":"' + path + '"}';
ws.send(data);
break;
}
})
ws.on("close", function() {
console.log("Browser gone.")
})
});
But the error is still here, i don't understand why
Take script part away from your client:
var sock = new WebSocket("ws://localhost:8005");
Server app is running in that port and all you need is to connect to the port.

( Socket.io ) One socket connection multiple rooms

I'm having problems with socket.io.
I try to create a single socket connection where this is connected to multiple rooms.
This is my current code:
function JoinRoom(id){
socket = io(domain);
  socket.on('connect', function (data) {
console.log('Connected to ' + room);
socket.emit('room', room);
});
socket.on('message', function (data) {
console.log(data);
});
}
The problem is that if I remove the var socket.io(domain) function was not connected and do not receive data from the room.
Example:
socket = io(domain);
function JoinRoom(id){
  socket.on('connect', function (data) {
console.log('Connected to ' + room);
socket.emit('room', room);
});
socket.on('message', function (data) {
console.log(data);
});
}
If I take the socket.io() function of the JoinRoom() function I do not receive messages message or anything. It does not work.
What am I doing wrong? Any solution?
On the client, create an event to indicate the access room.
On the server, apply the access logic.
Client
var socket = io('http://localhost');
function JoinRoom(data){
socket.emit("join", data);
}
var data = {
room:'ejemplo'
};
JoinRoom(data);
Server
var io = require('socket.io')(app);
io.on('connection', function(socket){
socket.on('join', function(data){
console.log(data); // data = { room: String, ...}
socket.join(data.room);
});
socket.on('leave', function(data){
socket.leave(data.room);
});

How to reuse TCP Client for further use in node.js

I am using a TCP connection via node.js to connect to a certain port in windows, however I want the connection to be established until the user logs out .
In other words I want to add the TCP Connection as a session attribute in node.js ,so that it will last as long as the session is alive for the user.
I have tried this ,but it doesn't work.
Code :
var express = require('express');
var authRouter = express.Router();
var createTCPConnection = function () {
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 6969;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
client.write('I am Chuck1 Norris!');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
// Close the client socket completely
//client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
return client;
};
authRouter.route('/').get(function(req, res) {
var sess = req.session;
if (sess.username) {
//If Session has username attribute, it is a valid session
res.render('dashboard', {
title : 'Welcome To Operator Screen',
username : sess.username
});
if(sess.tcpClient === undefined) {
console.log('Establishing TcpClient');
sess.tcpClient = createTCPConnection();
} else {
console.log('TcpClient already established');
}
} else {
//Invalid/expired session, redirect to homepage
res.redirect('/logout');
}
});
module.exports = authRouter;

socket.io doesn't receive data

I have a simple client server web app that is using web sockets to send / receive information. The client can connect and receives properly the config file but then when I try to send a "test' message from the client using "socket.emit('message', {my: 'data'});" it doesn't display on the server. I did check with wireshark and the packets are arriving at the server.
var sIoPort = 8181;
var host = '192.168.4.111';
var fs = require('fs');
var iniMsg = fs.readFileSync('data.json','utf8');
var http = require("http").createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(index);
});
http.listen(sIoPort,host);
var browserServer = require('socket.io').listen(http);
browserServer.on('connection', function (socket) {
console.log('Client websocket connected');
// send the config file if available
browserServer.sockets.emit('msg',iniMsg.toString());
});
browserServer.on('message', function (message) {
console.log('received message: ' + message);
});
client side
///////////////////////////////////////////////////////////////////////////////
socket = io.connect("192.168.4.111",{"port":8181});
socket.on('connect',function() {if(DEBUG) console.log('Socket Connected');});
socket.emit('message', {my: 'data'}); // test if server receives message
socket.on('msg',function(data) {
var json = JSON.parse(data);
// add the maps to the the GUI
switch(json.type) {
case 'maps': add_maps_from_json(json, null);
break;
}
});
socket.on('disconnect',function() {if(DEBUG) console.log('Socket Disconnected');});
/////////////////////////////////////////////////////////////////////////////////
Modify the serverside listener so it's paying attention to events on a socket:
browserServer.on('connection', function (socket) {
console.log('Client websocket connected');
// send the config file if available
browserServer.sockets.emit('msg',iniMsg.toString());
socket.on('message', function (message) {
console.log('received message: ' + message);
});
});

Categories

Resources