Node js server not working - javascript

I am trying to make a node js server with ws module. But it's not working. It says upgrade required.
My server side code:
var WebSocketServer = require('ws').Server;
wss = new WebSocketServer({port: 8080});
wss.on('connection', function(ws) {
ws.on('message', function(message) {
console.log('Msg received in server: %s ', message);
});
ws.send('Msg from server');
});
Client side code:
var WebSocket = require('ws');
var ws = new WebSocket('ws://localhost:8080/');
ws.on('open', function() {
ws.send('Msg from client');
});
ws.on('message', function(data, flags) {
console.log('Msg received in client: %s ', data);
});

Running npm update as an administrator should update the packages and solve your issue.
Here is a similar issue reported fixed by another user.

I didn't able to fix the problem. Then I used Socket.io. It works well.

Related

socket io not receiving events for both client and server

I followed the socket io website and implement client and server, below is my code
server
const exp = require('express')();
const http = require('http').createServer(exp);
const io = require('socket.io')(http,{
cors : {
origin : '*'
}
});
http.listen(3000, () => {
console.log('listening on *:3000');
setInterval(function(){
io.sockets.emit('hi', 'everyone');
},1000);
io.sockets.on('connection', function (socket) {
socket.on('hello', function (msg) {
console.log(msg);
});
});
});
client
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.4.0/socket.io.js" integrity="sha512-Y8KodDCDqst1e8z0EGKiqEQq3T8NszmgW2HvsC6+tlNw7kxYxHTLl5Iw/gqZj/6qhZdBt+jYyOsybgSAiB9OOA==" crossorigin="anonymous"></script>
<script>
let socket = io('http://localhost:3000',{
transports : ['websocket']
});
socket.on('hi', function(msg) {
console.log(msg);
});
socket.emit('hello','Hello server, im client');
socket.on('connect', function() {
console.log(socket.connected); // true
});
</script>
neither event hi nor hello arrived nor received from and to both client and server, no error whatsoever when running the script and client connecting to server. Any help is greatly appreciated.
Make sure to use matching socket.io versions: On your client you use 2.4.0, so install the same version on your server (npm install socket.io#2.4.0).
In the changelog for 2.4.0 you can see how you have to set cors options:
const io = require('socket.io')(http, { origins: "http://localhost:5000" });
You can't use "*" anymore, use your client domain. In newer versions the interface changed.
If you're not using version 2.4.0, the problem could also be the "*" wildcard.

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

Socket.io client cant connect to server

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.

Node.js Server crashed when Refresh Browser

I tried to build a chat box server by node.js. When the browser requestes the page, it workes well at first. But when I refresh the page, the Server crashes.
Below is the error message:
events.js:183
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at _errnoException (util.js:1022:11)
at TCP.onread (net.js:615:25)
I used the node --inspect index.js, but could not find the point.
Below is the code of index.js:
const http = require('http');
const fs = require('fs');
const extract = require('./extract');
const wss = require('./websockets-server');
var handleError = function (err,res) {
res.writeHead(404);
res.end();
}
var server = http.createServer(function (req, res) {
console.log("Responding to a request.");
var filePath = extract(req.url);
console.log("filePath:"+filePath);
fs.readFile(filePath,function (err,data) {
if(err){
handleError(err,res);
return;
}else {
res.end(data);
}
})
})
server.listen(3000);
When I comment the 4th line, the import of websockets-server. Server works well when I refresh the page. Maybe it's about the websocket while it works without websocket.
Below is code of websockets-server.js:
const WebSocket = require('ws');
var WebSocketServer = WebSocket.Server;
var port = 3001;
var ws = new WebSocketServer({
port:port
});
var message = [];
console.log('websockets server started');
ws.on('connection', function (socket) {
console.log('client connection established');
message.forEach(function (msg) {
socket.send(msg);
})
socket.on('message', function (data) {
console.log('message received: ' + data);
message.push(data);
ws.clients.forEach(function (clientSocket) {
clientSocket.send(data);
});
});
});
Does the problem is about the websocket? Whether should I do process when the client shutdown the connection with the server while refreshing the page.
extract.js below:
const path = require('path');
var extractFilePath = function (url) {
var filePath;
var fileName = 'index.html';
if(url.length > 1){
fileName = url.substring(1);
}
console.log('The fileName is: ' + fileName);
filePath = path.resolve(__dirname, 'app', fileName);
return filePath;
}
module.exports = extractFilePath;
I guess that you maybe execute var ws = new WebSocket("ws://localhost:3001"); in html file. I haven't figured out exact reason about your error as I'm not proficient in WebSocket. But there is a solution:
window.onbeforeunload = function () {
ws.close();
}
close connection before reload, then the error will not reappear.
You need to add an error listener on the socket. Error listener only on the websocket instance does not help in this case.
socket.on('error', function(e){
console.log(e);
});
The ECONNRESET error means that the other side (browser) closed the connection abruptly. On browser refresh, browser simple killed the connection with the websocket server.
To solve this, you have to listen for the error event on the websocket server instance.
// listen for "error" event so that the whole app doesn't crash
wss.on("error", function(error){
console.log(error);
}
I was having the same problem, but it resolved after this command:
npm install #ionic/app-scripts#nightly --save-dev

Connecting to a test websocket server works, but connecting to my Node.js server fails

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.

Categories

Resources