WebSocket connection timing out - javascript

I'm writing a WebSocket connection between a JavaScript client and node.JS server.
My client code:
<!DOCTYPE html>
<html>
<head>
<title>Socket Test</title>
</head>
<body>
</body>
<script>
const ws = new WebSocket('wss://mydomain.in:26031/');
ws.onopen = function () {
console.log('WebSocket Client Connected');
ws.send('Hi this is web client.');
};
ws.onmessage = function (e) {
console.log("Received: '" + e.data + "'");
};
</script>
Server code:
const net = require('net');
const server = net.createServer((socket) => {
socket.on('data', (data) => {
console.log(data.toString());
});
socket.write('SERVER: Hello! This is server speaking.\n');
socket.end('SERVER: Closing connection now.\n');
}).on('error', (err) => {
console.error(err);
});
server.listen(26031, () => {
console.log('opened server on', server.address().port);
});
The error i'm Getting:
WebSocket connection to 'wss://mydomain.in:26031/' failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT
I tried other answers in stack overflow, but everything seems perfect from my side. The server port is open for accepting request. What else might be wrong?

Use "wss://" only when you have SSL install
Or else try with ws://
You can also try using Socket.IO for socket connection.

Related

WebSocket connection is taking long time and failed

I created a secure websocket using this,
const Socket = require("websocket").server
const https = require("tls")
const fs = require('fs');
//certificate information
const certificate = {
cert: fs.readFileSync("/home/WebRTC/ssl/webrtc.crt",'utf8'),
key: fs.readFileSync("/home/WebRTC/ssl/webrtc.key",'utf8')
};
const server = https.createServer(certificate,(req, res) => {})
server.listen(3000, () => {
console.log("Listening on port 3000...")
})
const webSocket = new Socket({ httpServer: server })
and created the web client using this,
const webSocket = new WebSocket("wss://ip:3000")
webSocket.onerror= (event) => {
alert("Connection error occured");
}
webSocket.onopen = (event) =>{
alert("Connection established");
}
webSocket.onmessage = (event) => {
alert("Message received");
}
Im using https. Created a self signed certificate
wss://ip:3000. here the IP is the certificate resolving IP. These files are hosted in a publicly accessible server
But when I put the request, it takes a lot of time and gives and error.
"WebSocket connection to 'wss://ip:3000/' failed: "
Please be kind enough to help

How to get TCP client-server application to work across PCs

I want to know how two systems can communicate over tcp.
I have node.js tcp client and server codes. When tested on the same machine, the applications work well.
The problem is when I try to run the server code on one machine and the client code on another machine, no connection is established.
The two PCs are running on Windows and are connected using switch. They can share resources.
Please any help to understand how this things work is highly appreciated.
Here is the server code
const tcpServer = net.createServer();
const PORT = 3030;
const HOSTNAME = '169.254.142.199';
tcpServer.on('listening', () => {
console.log(`Server listening on port ${PORT}`, tcpServer.address());
})
tcpServer.on('connection', socket => {
console.log(`Server connected to client on localport ${socket.localPort} and remotePort ${socket.remotePort}`);
socket.on('error', err => {
console.log(`error occured ${err.message}`);
})
socket.write('Hi Welcome');
});
tcpServer.once('close', () => {
console.log('connection closed');
});
tcpServer.on('error', err => {
console.log(`error occured ${err.message}`);
});
tcpServer.listen(PORT, HOSTNAME);
Here is the client code
const PORT = 3030;
const HOSTNAME = '169.254.142.199';
const tcpClient = net.createConnection(PORT, HOSTNAME, () => {
console.log(`connected to server on port ${PORT}`, tcpClient.address());
});
tcpClient.on('error', err => {
console.log(`error occured: ${err.message}`);
})
tcpClient.on('close', err => {
console.log(`connection closed ${err ? 'with' : 'without'} error`);
})
tcpClient.on('data', data => {
console.log('%s', data);
})
169.254.142.199 is the IP address of the PC running the server code.
The error message is error occured: connect ECONNREFUSED 169.254.142.199:3030
What am I doing wrong? Where am I missing it?
Thanks for your help.
Finally it has worked.
I turned off Windows firewall and communication went through.
thanks to everyone.

How can i send data from a UDP server to a browser?

I try to make an application that receives from a third part application UDP packets.
I try to create a server UDP in NodeJS, but now when I receive the data I don't know how can I show it in a browser windows.
I explain better...my application receives data via udp in real time, the server processes them and should show them real time on a web page.
This is my code for UDP server in NodeJS:
const dgram = require('dgram');
const server = dgram.createSocket('udp4');
server.on('error', (err) => {
console.log(`server error:\n${err.stack}`);
server.close();
});
server.on('message', (msg, rinfo) => {
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
console.log(` messaggio ricevuto ${msg}`);
});
server.on('listening', () => {
const address = server.address();
console.log(`server listening ${address.address}:${address.port}`);
});
server.bind({
adress:'127.0.0.1',
port:'41234'
});
// server listening address :41234
Thanks a lot for the reply
welcome to SO!
You could do something like below...
// Open a connection
var socket = new WebSocket('ws://localhost:41234/');
// When a connection is made
socket.onopen = function() {
console.log('Opened connection πŸŽ‰');
// send data to the server
var json = JSON.stringify({ message: 'Hello πŸ‘‹' });
socket.send(json);
}
// When data is received
socket.onmessage = function(event) {
console.log(event.data);
}
// A connection could not be made
socket.onerror = function(event) {
console.log(event);
}
// A connection was closed
socket.onclose = function(code, reason) {
console.log(code, reason);
}
// Close the connection when the window is closed
window.addEventListener('beforeunload', function() {
socket.close();
});
This link should give you more info : https://www.sitepoint.com/real-time-apps-websockets-server-sent-events/ (above snippet is taken from this link)
You need a web server to send data to browser.
This link https://socket.io/get-started/chat will help you create a webserver.
You could send the message received on UDP port to the websocket as below
server.on('message', (msg, rinfo) => {
socket.emit('sendData', msg);
});

unable to create simple websocket - NodeJS

I am trying to follow this tutorial: https://www.simonewebdesign.it/101-web-socket-protocol-handshake/ for developing simple websocket protocol.
I am visiting localhost:1337/index.html but I get:
This localhost page can’t be found
No web page was found for the web address: http://localhost:1337/index.html
Search Google for localhost 1337 index
HTTP ERROR 404
if I visit this url: file:///C:/Users/.../websocket-demo/index.html
I atleast see the index.html page being rendered. But in console I get this error:
WebSocket connection to 'ws://localhost:1337/' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
I am not sure what's wrong?
I have 3 files: index.html, server.js and client.js
server.js
#!/usr/bin/env node
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
console.log('Received request from ' + request.url);
response.writeHead(404);
response.end();
});
server.listen(1337, function() {
console.log('Server is listening on port 1337.');
});
wsServer = new WebSocketServer({
httpServer: server,
autoAcceptConnections: false // because security matters
});
function isAllowedOrigin(origin) {
console.log('Connection requested from origin ' + origin);
valid_origins = [
'http://localhost:8080',
'127.0.0.1',
'null'
];
if (valid_origins.indexOf(origin) != -1) {
console.log('Connection accepted from origin ' + origin);
return true;
}
console.log('Origin ' + origin + ' is not allowed.')
return false;
}
wsServer.on('connection', function(webSocketConnection) {
console.log('Connection started.');
});
wsServer.on('request', function(request) {
var connection = isAllowedOrigin(request.origin) ?
request.accept('echo-protocol', request.origin)
: request.reject();
connection.on('message', function(message) {
var response = '';
console.log('Received Message: ' + message.utf8Data);
if (message.type === 'utf8') {
switch (message.utf8Data) {
case 'hi':
response = 'Hey there';
break;
case 'hello':
response = 'Heya!';
break;
case 'xyzzy':
response = 'Nothing happens.';
break;
case 'desu':
response = 'Keep typing, man. Keep typing.';
break;
default:
response = "Hello. Uh... what am I supposed to do with '" +
message.utf8Data + "'?";
}
connection.sendUTF(response);
}
});
connection.on('close', function(reasonCode, description) {
console.log(connection.remoteAddress + ' has been disconnected.');
});
});
client.js
(function () {
var ws = new WebSocket('ws://localhost:1337', 'echo-protocol');
ws.onopen = function (event) {
console.log('Connection opened.');
}
ws.onmessage = function (event) {
console.log('Response from server: ' + event.data);
}
ws.onclose = function (event) {
console.log('Connection closed.');
}
ws.onerror = function (event) {
console.log('An error occurred. Sorry for that.');
}
WebSocket.prototype.sendMessage = function (message) {
this.send(message);
console.log('Message sent: ' + message);
}
document.getElementById('send').addEventListener('click', function (event) {
event.preventDefault();
var message = document.getElementById('message').value;
ws.sendMessage(message);
});
})();
index.html - consist of forms
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>WebSocket Client Demo</title>
</head>
<body>
<h1>WebSocket Client</h1>
<form>
<label for="message">Send a message</label>
<input id="message" name="message" type="text">
<button id="send" name="send">Send</button>
</form>
<script src="client.js"></script>
</body>
</html>
Your web server doesn't serve your index.html file.
You can see this post to get an idea how to serve static files, or you can just boot up another HTTP server to serve your index file, like with python, the way they suggested in the README file of the tutorial that you are following: https://github.com/simonewebdesign/websocket-demo

node net socket timeout error on client

This is my server side code which has been hosted on IBM Bluemix,
const net = require('net');
const server = net.createServer((c) => { //'connection' listener
console.log('client connected');
c.on('end', () => {
console.log('client disconnected');
});
c.write('hello\r\n');
c.pipe(c);
});
server.listen(8124, () => { //'listening' listener
console.log('server bound');
});
I am using below code as client on local,
var net = require('net');
var HOST = 'xxx.xx.xx.xx';
var PORT = xxxx;
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 Chuck Norris!');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log('DATA: ' + 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');
});
When I run, It throws error Like.
events.js:141
throw er; // Unhandled 'error' event
^
Error: connect ETIMEDOUT xxx.xx.xx.xx:xxxx
at Object.exports._errnoException (util.js:856:11)
at exports._exceptionWithHostPort (util.js:879:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1063:14) vivek#vivek-Latitude-E6220:/var/www/html/test/NODE/net$ node client.js
events.js:141
throw er; // Unhandled 'error' event
^
Error: connect ETIMEDOUT xxxx.xx.xx.xx:xxxx
at Object.exports._errnoException (util.js:856:11)
at exports._exceptionWithHostPort (util.js:879:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1063:14)
When I run the server code on local, It works perfect. Kindly help me to find the error.
You need to listen on the port that Bluemix assigns for your application. Bluemix will assign your application a port and you will need to bind on that port. Bluemix will load balance to your application and have your application available on ports 443 and 80.
You can get the port with the following code.
var port = process.env.PORT || 8124;
Also you don't need to bind to a host either.
I modified your code below.
const net = require('net');
const server = net.createServer((c) => { //'connection' listener
console.log('client connected');
c.on('end', () => {
console.log('client disconnected');
});
c.write('hello\r\n');
c.pipe(c);
});
var port = process.env.PORT || 8124;
server.listen(port, () => { //'listening' listener
console.log('server bound');
});
The client code tries to connect to the server at the wrong address. Make sure that the client code's IP address and port number match the server's IP address and port number.
Also, ensure that the server is running and that the network connection between the server and the client is open. If the issue persists, try using a different port number and make sure the port is available on the server.
There is a read ECONNRESET Error in your server, when client destroy the socket.
you can catch using
c.on('error', function(err) {
console.log('SOCKET ERROR : ' , err);
});
you can avoid the crash this way.
working version for me, based on your code
server.js
const net = require('net');
var server = net.createServer(function(c) {
console.log('client connected');
c.on('end', function(c) {
console.log('sendHomeKeytoIosDevice : ERROR : ' + c);
});
c.on('error', function(err) {
console.log('sendHomeKeytoIosDevice : ERROR : ' + err);
});
c.write('hello\r\n');
c.pipe(c);
});
server.listen(8124,function() {
console.log('server bound');
});
Client.js
var net = require('net');
var HOST = 'localhost';
var PORT = 8124;
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 Chuck Norris!');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log('DATA: ' + 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');
});

Categories