Skip to content Skip to sidebar Skip to footer

Can't Create A Websocket Sever Correctly By Express-ws Middleware

I'm writing a websocket server using node.js and express, and I use the express-ws middleware to help me. But the client can't connect the server.Below is my code. app.js: var app

Solution 1:

Are you doing an app.listen(3000) in app.js to open that port? Websockets are just an upgrade to HTTP(s) so you can run on the same port as the rest of your routes.

Your server-side code is fine by the looks of it - not sure about client-side though. This works fine and outputs 'socket from client' when opened:

app.js

var express = require('express');
var app = express();
var expressWs = require("express-ws")(app);
var webso = require("./ws.js");
app.use("/chat",webso);
app.listen(3000);

ws.js

var express = require('express');
var router = express.Router();
router.ws("/",function(ws,req){
  console.log("socket from client")
  ws.on('message',function(msg){
    ws.send('back from node');
  })
});
module.exports=router;

test.htm

<scripttype="text/javascript">
    websocket = newWebSocket('ws://localhost:3000/chat');
</script>

Post a Comment for "Can't Create A Websocket Sever Correctly By Express-ws Middleware"