user2986042
user2986042

Reputation: 1270

why web socket behave differently on nodejs ?

I have a Nodejs Server.js code :

first Concept :

var http = require('http');
var express = require('express');
var app = express();
var path = require('path');

var conn= http.createServer(app).listen(3000, function () {
  console.log("server Running at Port 3000");
});

var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({server: conn});

and i have a index.html code with java script :

<html>
<body> 

<script src="myscript.js"></script>

</body>
</html>

inside myscript.js i have :

var connection = new WebSocket('ws://localhost:3000');

This is working fine when i open http://localhost:3000 on browser .

second Concept :

my server.js :

var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({ port: 3000}) ;

wss.on('connection', function (connection) {

});

wss.on('listening', function () {
    console.log("Server started...");
});

and HTML and client java script is similar as above .

This is not working when i open http://localhost:3000 on browser . why ? i want to clarify my doubt . Why the first method working and second is not working ?

Upvotes: 1

Views: 1924

Answers (1)

rsp
rsp

Reputation: 111336

To specifically answer your question: why web socket behave differently on nodejs? the answer is: It shouldn't. In the second version of your code you are not serving any HTML or JS files to the client on the port 3000 so the browser can't download any HTML.

If you want it to work as expected then you need to serve some HTML and JS files to the browser that visits http://localhost:3000/ or otherwise it will not be able to connect.

I wrote some example code - both server-side and client-side - on how to use WebSocket to do exactly what you are trying to do here. It's available on GitHub and I originally wrote it for this answer: Differences between socket.io and websockets.

The relevant parts of the source code for your question here are:

WebSocket Server

WebSocket server example using Express.js:

var path = require('path');
var app = require('express')();
var ws = require('express-ws')(app);
app.get('/', (req, res) => {
  console.error('express connection');
  res.sendFile(path.join(__dirname, 'ws.html'));
});
app.ws('/', (s, req) => {
  console.error('websocket connection');
  for (var t = 0; t < 3; t++)
    setTimeout(() => s.send('message from server', ()=>{}), 1000*t);
});
app.listen(3001, () => console.error('listening on http://localhost:3001/'));
console.error('websocket example');

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/ws.js

WebSocket Client

WebSocket client example using vanilla JavaScript:

var l = document.getElementById('l');
var log = function (m) {
    var i = document.createElement('li');
    i.innerText = new Date().toISOString()+' '+m;
    l.appendChild(i);
}
log('opening websocket connection');
var s = new WebSocket('ws://'+window.location.host+'/');
s.addEventListener('error', function (m) { log("error"); });
s.addEventListener('open', function (m) { log("websocket connection open"); });
s.addEventListener('message', function (m) { log(m.data); });

Source: https://github.com/rsp/node-websocket-vs-socket.io/blob/master/ws.html

Instead of debugging a code that it not working, sometimes it's better to start from something that works and go from there. Take a look at how it all works and feel free to change it and use it in your projects - it's released under MIT license.

Upvotes: 2

Related Questions