nodejs net client socket reconnect - javascript

var socket = new net.Socket();
socket.connect(PORT, HOST, function() {
console.log("SOCKET CONNECTED TO: " + HOST + ":" + PORT);
socket.write("Hello World!");
});
socket.on("error", function() {}); // need this line so it wont throw exception
// Add a "close" event handler for the client socket
socket.on("close", function() {
console.log("Connection lost. How do I reconnect? setTimeout?");
});
How do I reconnect after it failed? Now if the connection is not successful, everything stops..
I've tried using setTimeout in close event, but then when the socket connects, the 'connect' event is fired multiple times..

You could achieve reconnecting in the following way while keeping the event binding:
function connect() {
var socket = new net.Socket();
socket.connect(PORT, HOST, function() {
console.log('SCOEKT CONNECTED TO: ' + HOST + ':' + PORT);
socket.write('Hello World!');
});
socket.on('error', function() {}); // need this line so it wont throw exception
// Add a 'close' event handler for the client socket
socket.on('close', function() {
connect();
});
}
connect();

Related

Why Websocket connection is disconneting after sending message on iOS 15 devices?

I am building a website based on web socket communication. Its is working fine until iOS 14 but started breaking from iOS 15. Web socket java script client is able to open connection to server, but upon trying to send a message, the connection is getting closed. Following is my html and JS code.
function start_websocket() {
connection = new WebSocket("wss://localhost/wss/");
connection.onopen = function () {
console.log('Connection Opened');
};
connection.onerror = function (error) {
console.log('WebSocket Error ' + error);
};
connection.onclose = function(){
console.log("Closed");
};
connection.onmessage = function (e) {
console.log("Message Received :" + e.data);
};
}
function myFunction() {
var testText = document.getElementById("testText");
if (testText.value != "" && connection.readyState === connection.OPEN) {
connection.send("Test");
}
}
start_websocket();
myFunction() is an on-click event of a button.
A Java Websocket server is used, which will decode and send the messages based on the Data framing in https://datatracker.ietf.org/doc/html/rfc6455#section-5.
Saw different articles on the Web, but didn't found a solution to this issue. Any suggestions are much appreciated. Looking forward for your answers
Thanks in advance.

Why my messages are being displayed many times?

I made a chat room using electron. But when I send a message to the server and from there the message will be displayed to the users for some reason the message is being displayed multiple times. Example: I send -> "hello" the message will be displayed once, when I send a second message ->"Hello server" the message will be display two times, when I sent a third message ->"ok" this message will be displayed three times. The fourth message will be displayed 4 times etc.
this is the renderer.js code:
const ws = new WebSocket("ws://127.0.0.1:5000");
ws.addEventListener('open', function(event){
ws.send('hello server');
console.log("data sent");
});
function send_data(){
console.log("button clicked");
ws.send(document.getElementById("input_text").value);
ws.addEventListener('message', function(event){
console.log("server send something");
let mess=event.data;
console.log(mess);
update_chat(mess);
});
};
function update_chat(mess){
const div = document.createElement('div');
div.classList.add('message');
div.innerHTML = `okwpegjwpgj said: ${mess}`;
document.querySelector('.chat_messages').appendChild(div);
}
this is the server.js code:
const WebSocket = require('ws');
let broadcast_msg;
const PORT = 5000;
const wss = new WebSocket.Server({
port: PORT
});
wss.on("connection", ws =>{
ws.on('message', function incoming(message){
broadcast_msg=message;
console.log('received: ', message);
ws.send(message);
});
});
console.log("Server is liestening on port " + PORT);
Because you add the addEventListener('message') on every send_data() call.
Add the eventlistener once and remove it from the send_data() method. you don't need to add a new eventlistener every time you send data.
ws.addEventListener('message', function(event){
console.log("server send something");
let mess=event.data;
console.log(mess);
update_chat(mess);
});
function send_data(){
console.log("button clicked");
ws.send(document.getElementById("input_text").value);
};
Change your renderer.js file to this:
const ws = new WebSocket("ws://127.0.0.1:5000");
ws.addEventListener('open', function(event){
ws.send('hello server');
console.log("data sent");
});
ws.addEventListener('message', function(event){
console.log("server send something");
let mess=event.data;
console.log(mess);
update_chat(mess);
});
function send_data(){
console.log("button clicked");
ws.send(document.getElementById("input_text").value);
};
function update_chat(mess){
const div = document.createElement('div');
div.classList.add('message');
div.innerHTML = `okwpegjwpgj said: ${mess}`;
document.querySelector('.chat_messages').appendChild(div);
}

Nodejs, express & socket.io communicate between two static client pages

i am trying to build a remote for a gallery by using nodejs, express & socket.io.
the structure is as follows
/index.js
/public/screen.html
/screen.js
/remote.html
/remote.js
the idea is to have a gallery of images displayed on remote.html, select one and send the selected index to screen.html by using socket.io.
as of now my code looks like this:
index.js
var express = require('express');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io').listen(server);
app.use(express.static('public'));
server.listen(8080, function(){
// setup image gallery and stuff...
connectToServer();
});
remote.js
var socket = null;
document.addEventListener("DOMContentLoaded", function(event) {
//some stuff
connectToServer();
});
function showImage (index){ //called by events
console.log('selected incdex: ' + index);
if(socket != null) {
socket.emit('selection', {id: index});
};
}
function connectToServer(){
socket = io.connect('http://localhost:8080');
socket.on('connection', function (socket) {
var text = document.querySelector('#name');
socket.emit('newRemote', 'new remote connected');
console.log('emitted welcome');
socket.on('newScreen', function (data) {
console.log(data);
});
});
}
screen.js
var socket = null;
document.addEventListener("DOMContentLoaded", function(event) {
//some stuff
connectToServer();
});
function connectToServer(){
socket = io.connect('http://localhost:8080');
socket.on('connection', function (socket) {
var text = document.querySelector('#name');
socket.emit('newScreen', { name: name });
socket.on('newRemote', function (data) {
console.log(data);
});
});
};
when starting with node index.js i get
listening on *:8080
and when loading screen or remote.html i get
debug - client authorized
info - handshake authorized MwtGFRCZamcyKkUpK5_W
as I see it: somehow a connection is established, but:
no messages are sent / received on both ends
no logs are printed to the console for the connection events
any idea why nothing is happening?
It appears that you have mixed server-side code into your client. The 'connection' event is an event that needs to be listened to on the server, not your client files. Additionally, you cannot directly call client-side functions from your server-side code.
The below code does not work:
server.listen(8080, function(){
// setup image gallery and stuff...
connectToServer();
});
To achieve the above you will need to put the following code on your server:
server.listen(8080, function(){
socket.on('connection', function (socket) {
// setup image gallery and stuff...
socket.emit('connectToServer', myPassedParameters);
});
});
And the following listener for that event on the client:
socket.on('connectToServer', function (myPassedParameters) {
var text = document.querySelector('#name');
// stuff for client side here
});
});
In addition to the above, you cannot do calls from one client file to another client file using socket.io. You would have to do a call to the server first and then call a function on the other file once it has been loaded for the user.

My WebSocket doesnt work in Opera/Midori

everyone I'm creating an "Object" to manage all information about my socket connection but I've some problems about browser compatibilities
$(document).ready(function(){
socket.connect();
socket.connection.onopen = function(){
console.log('Connected '+ socket.connection.readyState);
//Show 1 for every browser
};
socket.connection.onmessage = function(event){
console.log('Some message '+event.data);
//Firefox / Chrome Fine
//Midori/Opera doesnt show this message (console)
};
});
var socket ={
dataConnection: {
url:"myURL",
param:"myParam"
},
connection: "",
connect: function(){
try{
this.connection = new WebSocket(this.dataConnection.url+"/"+this.dataConnection.param);
}catch(error){
console.log('Something wrong ' + error.message);
}
}
};
I don't understand Wy It works fine (FF and Chrome), Can you give an advice?

Reconnect hub necessary

I have simple project in ASP.NET Web site with signalr.
Code for start connection hub:
var scriptStarted = 'var myHub = $.connection.' + hubName + ';' + methodNameInitHub + '(myHub);';
$.connection.hub.error(function () {
alert("An error occured");
});
$.connection.hub.start()
.done(function () {
eval(scriptStarted);
myHub.server.registerClient($.connection.hub.id, clientIdentifier);
})
.fail(function () { alert("Could not Connect!"); });
This method is call in "methodNameInitHub + '(myHub);"
function methodInitEventHub(hub) {
if (hub) {
hub.client.addEvent = function (eventOperationName, eventType) {
$("#events").append("<li>" + eventOperationName + ", " + eventType + "</li>");
};
}
}
Code for stop connection hub:
$.connection.hub.stop();
When I load .aspx page and start hub all code execute without errors, but event from server not recieved.
After I stop and start again hub connection events begining received in client (browser)
http://clip2net.com/s/2CP2e
Why I need to restart connection hub for begin received event from server ?
Thanks.
The reason you're having issues is because you must have at least 1 client side hub function prior to calling start otherwise you will not be subscribed to the hub.
Try doing
myHub.client.foo = function() {}
prior to start.
The reason why it works after you stop then re-start the connection is because your script binds a new client method, hence allowing you to subscribe to the hub after you've restarted the connection.
Hope this helps!

Categories