Chrome WebSocket connection closes immediately - javascript

I have been trying to setup a wss server using nodejs, and have encountered a problem when trying to connect to it using chrome. The problem still occurs with all extensions disabled and in an incognito window so I've ruled that out as the problem.
When trying to connect using chrome, I get the error:
WebSocket connection to 'wss://www.domain-name.com/' failed:
with no reason given. On the server, socket.on('close') is called immediately with description "Connection dropped by remote peer" The close event has wasClean = false. This error does not occur when connecting from safari and Firefox so I'm not really sure where to look to see what's causing it. It's running on AWS Lightsail, and through an Apache proxy server.
The client code:
var socket = new WebSocket("wss://www.domain-name.com", 'JSON')
socket.onopen = function (event) {
console.log('open');
socket.send('socket opened')};
socket.onclose = function (event) {
console.log(event)};
socket.onmessage = function(message) {
console.log('receiving message from server...')};
And the server code:
const WebSocketServer = require('websocket').server;
app = express()
var server = app.listen(3000, () => {
console.log('Server started');
});
app.use(express.static('public'));
var wsServer = new WebSocketServer({
httpServer: server
});
wsServer.on('request', function(request){
console.log('New connection');
var connection = request.accept(null, request.origin);
connection.send('welcome from server...');
connection.on('message', function(message){
console.log(message)};
connection.on('close', function(reasonCode, description) {
console.log('disconnecting', reasonCode, description);
});
});
I also got the same error before switching to a secure WebSocket server. Any help would be appreciated, I've run out of places to look and ways to try and get more information to help out what the problem is.
EDIT: it seems to work on chrome on my phone, but not on chrome on my friends phone?

The problem was not specifying the protocol when accepting the connection. After about 20 hours working on the same bug and implementing an SSL certificate to get it to work, I changed:
request.accept(null, request.origin);
to:
request.accept('json', request.origin);
For some reason the chrome gives a really unhelpful error message. Microsoft edge the same error occurs, but gives a much more helpful error message so I could work out what was going on.

In my case, this was caused by passing an unused options value as the third parameter to the WebSocket constructor. The options parameter is supported by Node.js's ws module but not by browsers; however, instead of displaying a clean error message, Chrome closed the connection without a good description.

Related

Twilio: Could not connect to Live: Signaling connection disconnected

I use Twilio for a while, and today when I try to create a video Room,
The LED in my web cam appears then disappears and Twilio says this message:
Could not connect to Live: Signaling connection disconnected
When I do Inspect Element in Firefox I see this:
Firefox can’t establish a connection to the server at wss://sdkgw.us1.twilio.com/v1/VideoEvents.
This is how I used to connect with js
var connectOptions = {
name: room_name,
}
Twilio.Video.connect(token, connectOptions).then(roomJoined, function(error) {
var text = ('Could not connect to Live: ' + error.message )
ring('danger',text);
}
Does someone know what is wrong?
According to this bug report, this is possible if your token has expired. Instead of throwing a 20104, it throws 53000. Check your token. It was the same in my case.

secured connection between javascript client and python server

i have python server(with the help of asyncio and websockets module) and js client(with the help of websockets library) that are connected. The problem is that i need this connection to be secured (i'm working on passwords), but i had no success on establishing a connection with wss(web socket secure) - the code runs only with ws.
I even tried to establish my own encryption with RSA and AES but that also didn't work.
i'm really hopeles about it so if anyone ever did it or know a little about it, pls help me figure out what's wrong with it, or a direction to a rigth solution for secured connection that will work.
here's my server:
async def app(websocket, path):
while True :
data = await websocket.recv()
if (data== "close"):
print("connection with client closed.")
break
data = data.encode()
arr = data.split("~".encode())
for i in range(0,4):
arr[i]=arr[i].decode()
resualt=algo(arr)
await websocket.send(resualt)
start_server = websockets.serve(app, '0.0.0.0', 6169)
and my client:
var socket = new WebSocket("ws://127.0.0.1:6169/");
socket.onopen = function (evt) {
socket.send(st);
};
socket.onmessage = function (evt) {
alert("scrool extension page down to see the password");
$('#res').val(evt.data);
socket.send("close");
};
socket.onerror = function (evt) {
alert("the error is: "+evt.data);
};
in the python script we tried to use ssl:
c = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
c.load_default_certs(purpose=ssl.Purpose.CLIENT_AUTH)
start_server = websockets.serve(app, '0.0.0.0', 6169, ssl=c)
and in the js sciprt we wrote instead of the ws, wss:
"ws://127.0.0.1:6169/")
and the error we get:
WebSocket connection to 'wss://127.0.0.1:6169/' failed: Error in connection
establishment: net::ERR_CONNECTION_CLOSED

Cancel WebSocket connection when trying to connect (JavaScript)

Is it possible to cancel WebSocket connection while trying to establish connection to the server?
Let's say user notified that it is a misspelled host and want to cancel request for establishing connection before onerror has raised like
failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
I tried to call close, but this does not cancel request. I even get warning in console:
failed: WebSocket is closed before the connection is established.
Unfortunately, this is not achievable using close(), and seems not possible at all.
Also, unlike XMLHttpRequest, WebSocket have no abort method to achieve this.
The WebSocket specs do not mention any way of doing this, and setting the object to null does not do the trick.
The following example illustrates this by setting the WebSocket object to null, but still getting connection error message.
var ws = new WebSocket('ws://unknownhost.local');
ws.onopen = function() {
console.log('ohai');
};
ws = null;
console.log(ws);
// > null
// > VM2346:35 WebSocket connection to 'ws://unknownhost.local/' failed: Error in connection establishment: net::ERR_NAME_NOT_RESOLVED
Since the two previous answers to this question have been posted the behaviour of close() seems to have changed.
Quoting the mozilla API docs:
The WebSocket.close() method closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED, this method does nothing.
You could therefore do this:
var ws = new WebSocket('ws://unknownhost.local');
setTimeout(() => {
if (ws.readyState == WebSocket.CONNECTING) {
ws.close();
console.log("Connection cancelled.");
}
}, 1000);
Which would cancel the connection attempt if the readyState did not switch to OPEN yet.
I tried this, and it seems to work (tested on Firefox).
close() method only terminates the established connections.
For your case, you may use assigning your websocket handle to null where you want to stop it.
webSocketHanle = null;
By this assignment, your callbacks will not be activated.
But notice that it is quite fast process to getting response from server.

Firefox Nodejs Websocket

I am using Aurora 17, Chrome 22 and Firefox 16 and I am trying to create a simple chat app. I am using Node 0.8.9.
Firefox is getting the error that it cannot connect giving the error
Firefox can't establish a connection to the server at ws://localhost/.
I also tried it with the port and it have the same message
Firefox can't establish a connection to the server at ws://localhost:4444/.
Here is my code:
Server Code:
var http = require('http');
var net = require('net');
function onRequest(req, res) {
// Does enough to render a page and javascript
}
http.createServer(onRequest).listen(4444);
var socket = new net.Socket();
socket.connect(4444, "localhost", function(){
console.log("Socket Connected");
});
socket.on("message", function(message){
console.log(message);
});
Client Code:
var WebSocket = window.WebSocket || window.MozWebSocket;
var connection = new WebSocket('ws://localhost:4444');
connection.onopen = function() {
// Never runs
alert("This never runs :(")
}
connection.onerror = function(error) {
// Always runs here
console.log(error)
}
I get an output that the Socket is connect from the log statement on the server but Firefox cannot connect to the socket.
On Chrome, there is no error but the "onopen" is never fired. Using connection.send("a message") does not send anything to the server and returns false.
You're creating an ordinary TCP client socket in your server code and connecting it to your HTTP server. That's not at all the same thing as creating a WebSocket server that a browser can connect to. Use a library designed for the purpose (socket.io is very commonly used, since it can fall back to alternate transports when a browser doesn't support WebSockets).

"Error: write EPIPE" with Socket.io on node.js

I manually applied this patch and everything works now. Waiting on upstream to fix this
https://github.com/LearnBoost/socket.io-client/pull/361/files
I'm just trying to follow the examples given and trying to get this to work.
Mockserver.js:
var io = require('socket.io').listen(8000);
io.sockets.on('connection', function(client) {
console.log('+ new client');
client.on('disconnect', function() {
console.log('- lost a client');
});
});
Mockclient.js:
var io = require('socket.io-client');
var socket = new io.connect('localhost', { port: 8000 });
socket.on('connect', function() {
console.log('connected');
});
socket.on('message', function(data) {
console.log(data);
});
I then run these pair with node Mockserver.js and node Mockclient.js on another terminal
info - socket.io started
debug - client authorized
info - handshake authorized 14797776461130411158
debug - setting request GET /socket.io/1/websocket/14797776461130411158
debug - set heartbeat interval for client 14797776461130411158
debug - client authorized for
debug - websocket writing 1::
+ new client
debug - set close timeout for client 14797776461130411158
***************************** error occurs here ****************
info - socket error Error: write EPIPE
at errnoException (net.js:632:11)
at Object.afterWrite [as oncomplete] (net.js:470:18)
****************************************************************
debug - setting request GET /socket.io/1/xhr-polling/14797776461130411158?t=1325912082073
debug - setting poll timeout
debug - discarding transport
debug - cleared close timeout for client 14797776461130411158
debug - cleared heartbeat interval for client 14797776461130411158
debug - clearing poll timeout
info - transport end
debug- set close timeout for client 14797776461130411158
debug - cleared close timeout for client 14797776461130411158
at this point I stopped Mockclient.js
- lost a client
debug - discarding transport
The only output for "node Mockclient.js" is
The "sys" module is now called "util". It should have a similar interface.
What's causing the socket exception? I'm probably missing something pretty obvious. Also, can somebody else try my code to see if the errors on their machine as well? The code inside socket.on('connect'... isn't triggering either. I don't exactly know why.
Apply this patch
https://github.com/LearnBoost/socket.io-client/pull/361/files

Categories

Resources