Karric
Karric

Reputation: 1565

Basic Web Socket with ExpressJS and Jquery

I'm trying to build an ExpressJS websocket backend for a jQuery-based front end using HTML5 web sockets.

The ExpressJS backend code is literally copy-pasted from https://github.com/websockets/ws#expressjs-example

The javascript front end code is:

var socket = new WebSocket("ws://localhost:8080");

socket.onopen = function(){
    console.log( "OPENED : ", socket.readyState );
}

socket.onmessage = function(msg){
    console.log( msg );
}

socket.onclose = function(){
    console.log( "CLOSED : ", socket.readyState );
}

setTimeout(function(){
    socket.send('test');
}, 2000);

In Chrome, I'm receiving an error: "Connection closed before receiving a handshake response". I've looked online for a solution, but they are all socket.io based whereas I'm just using the NodeJS ws package.

Any tips would be greatly appreciated.

Upvotes: 1

Views: 1753

Answers (2)

madllamas
madllamas

Reputation: 518

The back end code :

const express = require('express')
const http = require('http')
const WebSocket = require('ws')
var path = require('path')

const app = express()

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname + '/a.html'))
})

const server = http.createServer(app)
const wss = new WebSocket.Server({ server })

wss.on('connection', function connection (ws, req) {
  ws.on('message', function incoming (message) {
    console.log('received: %s', message)
  })

  ws.send('something')
})

server.listen(8080, function listening () {
  console.log('Listening on %d', server.address().port)
})

the only change is the app.get on line 8 instead of the app.use provided in the link you gave.

And the a.html file has only the front end script :

<html>
  <head>

  </head>
  <body>
    <script>
      var socket = new WebSocket("ws://localhost:8080");

      socket.onopen = function () {
        console.log("OPENED : ", socket.readyState);
      }

      socket.onmessage = function (msg) {
        console.log(msg);
      }

      socket.onclose = function () {
        console.log("CLOSED : ", socket.readyState);
      }

      setTimeout(function () {
        socket.send('test');
      }, 2000);
    </script>
  </body>

</html>

And everything is working fine.

You said you are running the server on port 3000 and yet you are trying to connect to port 8080 in the front end code. Was that a mistake ?

Upvotes: 2

MeVimalkumar
MeVimalkumar

Reputation: 3361

use socket.io the fasted and most reliable, it is far more easy to implement and configure.

Upvotes: 0

Related Questions