socket io changes socket.id repeatedly - javascript

Is this normal behavior?
socket.io-1.3.2.js
From the client:
socket = io.connect('https://socket.myserver.nl');
socket.on('connect', function() {
socket.emit('register', userID, 'Lobby');//ignore this
});
At the server Node version v5.2.0:
io.sockets.on('connection', function (socket) {
console.log('SOCKET CONNECTING '+socket.id);
////lots of other code//////////
socket.on('disconnect', function() {
console.log('SOCKET DISCONNECTING '+socket.id);
});
});
During test when i make a single connection with a client to the server and further doing absolutely nothing i get the following (5 minutes approximately):
SOCKET CONNECTING SddHIXmWSeHEfDnlAAAC
SOCKET DISCONNECTING SddHIXmWSeHEfDnlAAAC
SOCKET CONNECTING o0zj7GE1tlO3RQw1AAAD
SOCKET DISCONNECTING o0zj7GE1tlO3RQw1AAAD
SOCKET CONNECTING lAnfvaF3DXMyhc6lAAAE
SOCKET DISCONNECTING lAnfvaF3DXMyhc6lAAAE
SOCKET CONNECTING tP3cjtJ-VpPPjoG2AAAF
SOCKET DISCONNECTING tP3cjtJ-VpPPjoG2AAAF
SOCKET CONNECTING a2o13T7CgcKDEbppAAAG
SOCKET DISCONNECTING a2o13T7CgcKDEbppAAAG
SOCKET CONNECTING avogGTh0KVtLFOqNAAAH
SOCKET DISCONNECTING avogGTh0KVtLFOqNAAAH
SOCKET CONNECTING usoQGxKAMsth2zTcAAAI
SOCKET DISCONNECTING usoQGxKAMsth2zTcAAAI
question continues here: socket-io-changes-socket-id-repeatedly part 2

If you use React, Vue or something like that
Create another js file inside src and type these lines for connecting myCustomSocket.Export socket.id and socket. Because you need to run socket.io out of dynamic rendered components.
import { io } from 'socket.io-client';
export const socket = io('http://localhost:5000');
export let socketID = '';
socket.on('connect', () => {
socketID = socket.id
})
And inside React components you can import them.
import { socketID, socket } from './myCustomSocket';

Related

Close the socket.io connection when user changes route in Angular 8

Socket.io closes the connection when user try to close the tab or window but it does not when user navigate to other route in same angular app, the disconnect event will not fire in that case.
server-side:
io.on('connection', function (socket) {
console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconnected');
});
});
the socket.disconnect() method will not work.
I am trying to use CanDisconnect routing guards but does not know how to use that to close the connection.
server side:
// dependencies
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
//importing routes
var loginRouter = require('./routes/loginRoutes');
var chatRouter = require('./routes/chatRoutes');
app.use('/', loginRouter); // applying routes to the app
app.use('/', chatRouter); // applying routes to the app
// starting the server
http.listen(3000, function(){
console.log('server is listening on port '+PORT);
});
// socket.io ===================================
io_public = io.of('/public'); // namespace public
io_public.on('connection', function(socket){
socket.on('adduser', function(username){
socket.username = username;
socket.room = 'public'; //assign default public room
socket.join(socket.room);
socket.emit('server', 'you have connected to a public room');
socket.broadcast.to('public').emit('server',socket.username + ' has connected to this room');
});
socket.on('disconnect', function(){
socket.broadcast.to('public').emit('server',socket.username + ' has left the room');
socket.leave(socket.room);
});
});
client side:
var socket = io('http://localhost:3000/public');
var user = Cookies.get('user');
socket.on('connect', function(){
socket.emit('adduser', user);
});
socket.on('server',function(msg){
$('#conversation').append('<li> <b>Server: </b>'+msg+'</li>');
});
I am loading this client script in home component on dashboard/home, when user moves to dashboard/contacts it does not disconnect. It also create duplicate socket listeners also because this client script will reloaded every time the component is loaded.
starting state
move to contact routes:
Reloading home component
You can generate an Angular service for connecting and disconnecting. Call the service to Connect on the ngOnInit on the components you want and then call the disconnect method on the ngOnDestroy method.
You can also try to do the same implementing Guards like you said.
Inside component.ts
ngOnInit() {
this.chatService.connect()
}
ngOnDestroy(){
this.chatService.disconnectSocket();
}
Inside ChatService
import { io, Socket } from "socket.io-client";
private socket: Socket;
constructor() {
this.socket = io("http://localhost:4000");
}
connect(){
this.socket.connect()
}
disconnectSocket(){
this.socket.disconnect()
}

WebSocket stops working in Vue/Node application

I have a Node/Vue application. I am consuming a WebSocket from Binance, a crypto exchange. I can see the quotes on the server console as I log them, I can send them to the browser for a short period of time before the client stops logging them.
Browser just using WebSocket API
Node using ws library
Node code, this I am running as it's own service as its just this.
'use strict';
const WebSocket = require('ws');
const binanceWS = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt#trade')
const server = new WebSocket.Server({ port: 5002 });
//websocket connection event will return a socket you can later use
binanceWS.on("open", function() {
console.log("connected to Binance");
});
binanceWS.on('message', function(data){
console.log(data);
server.on('connection', function connection(ws){
console.log("Connected a new client");
ws.send(data);
});
server.on('closed', function (id){
console.log("connection closed");
console.log(id);
});
server.on('error', function (err){
console.log(err)
})
})
On the Client side I am using Vue and in the app.js file I have this on the created hook.
let socket = new WebSocket("ws://localhost:5002")
socket.addEventListener('message', function(event){
let quotes = JSON.parse(event.data);
console.log(quotes.p)
});
socket.addEventListener('error', function(event){
console.log("closing because " + event);
})
Right now I am only listening to the consoles in the above app.vue file.
What I see in the browser console is a lot of quotes, then they stop after a second or 2. There can be over a thousand quotes in some times. Then on occasion I see a console.log('created') that I have in a child component of app.vue. In many cases this is the last thing in the console after hundreds of quotes.
In the console.log for the server I see a lot of sessions being created with one page refresh. So much that it fills my console.
So I'm not sure I am creating the connections correcly, I am not sure if Vue is somehow stopping the console.log's?
I don't see any errors anywhere and the entire time in my server console the Binance API continues streaming.
you have to write server event listener outside binance on message handler;
then you can pass messages from binance to the server by emitting new event to the server
on receiving message from binance you can send data to all connection on the server
Or Try this code I think it will work :
'use strict';
const WebSocket = require('ws');
const binanceWS = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt#trade')
const server = new WebSocket.Server({ port: 5002 });
server.on('connection', function connection(ws){
console.log("Connected a new client");
});
server.on('closed', function (id){
console.log("connection closed");
console.log(id);
});
server.on('error', function (err){
console.log(err)
})
//websocket connection event will return a socket you can later use
binanceWS.on("open", function() {
console.log("connected to Binance");
});
binanceWS.on('message', function(data){
console.log(data);
server.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
})

Unable to connect to a websocket in node js

I have a websocket with URL "ws://localhost:1122" running in my machine. I am able to connect to the websocket when using it with normal javascript and deploying it in a jetty server.
But while using node js I could not connect to the web socket. I use the following code in both cases
var socket = new WebSocket(URL);
While using node js I have addded the following var WebSocket = require("ws"). But the readyState of the socket never become OPEN in node js.
Is there anything I am missing in node js because while using jetty as a server and normal javascript I am able to connect to the websocket.
Here is my app.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
}).listen(1131, "localhost");
var WebSocket = require("ws");
var wsUri = "ws://localhost:1122";
var socket;
printer();
function printer() {
socket = new WebSocket(wsUri);
console.log(socket.readyState);
}
Because of the asynchronous nature of Node.js, socket.readyState doesn't immediately reflect the state of the connection.
Instead, you should use the event emitter interface to check if/when the connection is being made:
socket = new WebSocket(wsUri);
socket.on('open', function() {
console.log('connection opened');
}).on('close', function() {
console.log('connection closed');
}).on('error', function(e) {
console.log('connection error', e);
});

communicate between two modules nodejs

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);
});

node.js connect to server socket, dont know how to authenticate with password

I am building a desktop audio streaming application, which will be a client, i wish to connect to a server socket to stream audio, i have the host ip, the port and password. I am using node to connect:
var client = net.connect(serverDetails, function() { //'connect' listener
console.log('client created!');
});
client.on('connect', function() {
console.log('connected to: '+serverDetails.host+' port: '+serverDetails.port );
//client.write(serverDetails.password+'\r\n');
});
client.on('data', function(data) {
console.log('sending data to server!');
console.log(data.toString());
});
client.on('end', function() {
console.log('disconnected from server');
client.end();
});
at the moment it connects and the disconnects straight away, how can i pass the password so that the connection remains open? after which i can stream/send data to this socket.

Categories

Resources