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;
Related
I have issue related to Socket.io connection to server.
Its working fine on my local, but on dev-server it cant connect.
My backend code look like this:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
server.listen(8080);
console.log('CONNECTED');
io.on('connection', function (socket) {
var handshake = socket.handshake;
console.log(handshake);
console.log("new client connected");
var redisClient = redis.createClient();
redisClient.subscribe('notification');
redisClient.subscribe('rate');
redisClient.on("message", function(channel, message) {
console.log("New message: " + message + ". In channel: " + channel);
socket.emit(channel, message);
});
socket.on('disconnect', function() {
redisClient.quit();
});
});
And my client part like this:
var socket = io.connect('http://localhost:8080');
socket.on('notification', function (data) { console.log(data) }
The error that im facing is when socket.io client tries to send to URL "http://localhost:8080/socket.io/?EIO=3&transport=polling&t=MD_W4lE" request and its failing, with error ERR_CONNECTION_REFUSED. The node server is runing i tested and also tried to change localhost to 127.0.0.1 and ipv4 address, i didnt helped.
Hello i am trying to emit command using SOCKET to user when setting gets changed through some API..
but I dont know how can i get socket or tell socket to emit the message to user..
Please Help
this is my code
//Socket INIT
class Socket{
constructor(){
//Init variables
}
start(){
//Start socket
this.io.use((socket, next) => this.auth.authDevice(socket, next));
this.io.on('connection',(socket) => this.conn.handleConn(socket));
}
}
//Socket Connection
let socketStack = [];
class Connection{
handleConn(socket){
// store client
socketStack[socket.userid] = socket
}
pushCmd(userid, command){
//cheeck if userid exists in >>socketStack<< and emit
}
}
//Command Emit
class Command {
constructor(id) {
this.userid = id.userid
//socket - Connection class
this.socketConn = new SocketHandler()
}
static push(userid, command) {
//i want to sent it to current socket context. this has empty socketStack..
this.socketConn.pushCmd(userid, command);
}
}
let socket = new Socket();
socket.start() //connection started, all clients connect to //this socket .. I WANT API to use this socket to emit something that //API sends....
You have to make socket to 'listen' on server. For example, I'm using express with node.js, and this is the way I run socket.io:
var app = express();
var server = require('http').createServer(app);
var io = socketio.listen(server);
io.on('connect', function (socket) {
socket.on('exampleCall', function () {
console.log("socket invoked!");
socket.emit("exampleEmit");
});
});
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function () {
var addr = server.address();
console.log("Server listening at", addr.address + ":" + addr.port);
});
I have a use case where I need to take input from browser pass it to my node server over a socket, this input is then send to a third party website for processing again over socket. The result received from the third party website needs to be sent back to browser.
node server
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var socketIO = require('socket.io'),
server, io;
var thirdPartSocketClient = require('socket.io-client');
//Custom imports
var thirdParty = require('./ms_socket.js');
var socket = socketIO(server);
socket.on('connection', function(client) {
var token = null;
//Token from third party site that we should have before sending the actual info
thirdParty.getToken(function callback(returnToken) {
token = returnToken;
});
thirdPartSocketClient = thirdParty.getTranslation(token);
client.on('audio', function(data) {
thirdPartSocketClient.emit(data);
});
});
server.listen(8080, function() {
console.log('Open http://localhost:8080 in your browser');
});
ms_socket.js
//Exported function making a socket call to third party service
var exports = module.exports = {};
var request = require('request');
var wsClient = require('socket.io-client');
var fs = require('fs');
exports.getToken = function(callback) {
//send back the token
}
exports.getTranslation = function(accessToken) {
var ws = new wsClient(thirdPartySocketURL);
// event for connection failure
ws.on('connectFailed', function(error) {
console.log('Initial connection failed: ' + error.toString());
});
// event for connection succeed
ws.on('connect', function(connection) {
console.log('Websocket client connected');
// process message that is returned
//processMessage would process the incoming msg from third party service
connection.on('message', processMessage);
connection.on('close', function(reasonCode, description) {
console.log('Connection closed: ' + reasonCode);
});
// print out the error
connection.on('error', function(error) {
console.log('Connection error: ' + error.toString());
});
});
// connect to the service
ws.connect(thirdPartySocketURL, null, null, {
'Authorization': 'Bearer ' + accessToken
});
return ws;
}; //End of export function
I am able to receive the data from browser, make a connection to third party service (can see the socket connection) and emit the data. however I am unable to receive the reply back from the third part service.
Is it because node is not listening to my socket events of thirdparty ?
Not sure exactly why its not working.
I save the data locally on the server, read the file and then send it, then I get a response back from the service.
If this is not a "right" design can you please suggest a good way, should I be using message queues (if yes, feel free to recommend one)
Thanks
I'm new to socket.io, and I'm doing a simple API with NodeJS (express 4). I'm developing an action that is similar to the old "poke" action at facebook. A user send a poke to other user, and this one gets a notification on real time (this is the reason why I am using socket.io).
This is the code:
app.js
var port = 3000;
var app = module.exports = express();
var server = require('http').Server(app);
...
server.listen(port);
require('./config/socket-io')(app, server, secret);
socket-io.js
module.exports = function(app, server, secret) {
var clients = {};
console.log("initiating sockets...");
var sio = require('socket.io').listen(server, {'log level': 2});
sio.on('connection', function (socket) {
console.log("...new connection: "+socket.client.id);
clients[socket.id] = socket;
socket.emit('identification', { data : socket.client.id });
socket.on('newShoutOut', function(data) {
var receptor = data.idTo;
var emiter = socket.client.id;
console.log("...new shout out from " +emiter+ " to "+receptor);
sio.sockets.sockets[receptor].emit({ data : data.data, from : emiter });
});
socket.on('disconnect', function() {
console.log("..."+socket.client.id + " disconnected");
});
});
};
Here you can differentiate three states:
Connection: The server detects all the clients connection to the host:port. After that, the server sends to each client his ID. This works fine.
Send message: One client sends a notification to other client. For now, the server receives the notification from one client, but the "receiver" doesn't receive anything.
Disconnection: Doesn't matter in this case.
My question is, what is the way to send a message to a client directly knowing the ID? What I am doing wrong? I tried so many options to send a message directly to a specific client ID but didn't work...
EDIT
Frontend
var socket = io('http://localhost:3000');
var id = "";
socket.on('connection', function (data) {
console.log("connected!");
console.log(data);
});
socket.on('identification', function(data) {
id = data.data;
$("#socket_info h1").html("ID: "+id);
});
socket.on('newShoutOut', function(data) {
console.log("newShoutOut received!");
});
Ok, so I assume the shoutout is coming from a user? You will need to create the event on the clientside, such as:
var button = $('#button');
button.on('click', function() {
var msg = 'message',
userID = '123'; //get the ID who they are messaging
socket.emit('sendShoutOut', {msg: msg, id: userID});
});
Then you will need to receive that response on the server, and reply to the user in that function:
socket.on('sendShoutOut', function( data ) {
socket.sockets.sockets[data.id].emit('sendPrivateMsg', { data : data.msg, from : emiter });
});
Lastly, the reciever must be notified, so you will need to handle the response on the client:
socket.on('sendPrivateMsg', function( data ) {
alert(data);
});
Hope this helps.
I'm using the code below to test websockets on my browser:
this.webSocket = new WebSocket("ws://echo.websocket.org");
this.webSocket.onopen = function(evt) {
cc.log("Send Text WS was opened.");
};
this.webSocket.onmessage = function(evt) {
this.socketSendTextTimes++;
var textStr = "response text msg: " + evt.data + this.socketSendTextTimes;
cc.log(textStr);
};
The code works well, but if I connect to my own server running the code below:
var http = require('http');
var io = require('socket.io');
var server = http.createServer(function(req, res) {
// Send HTML headers and message
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end('<h1>Hello!</h1>');
});
var socket = io.listen(server);
socket.set('destroy upgrade', false);
socket.on('connection', function(client) {
client.on('message', function(event) {
console.log('Received message from client!', event);
});
client.on('disconnect', function() {
console.log('Server has disconnected');
});
});
server.listen(8080);
console.log('start to listen');
My browser displays:
hello!
But the listening socket does not do anything. How can I connect to the Socket.IO server using websockets?
Socket.IO uses alternate transport methods than the native websocket, even when emulating websockets themselves. You will need the client library to connect to Socket.IO sockets.