Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to setup route for websocket server in express?

I have a setup similar to this one:

var WebSocketServer = require("ws").Server,     express = require("express"),     http = require("http"),     app = express(),     server = http.createServer(app);  app.post("/login", login); app.get("/...", callSomething); // ...  server.listen(8000);   var wss = new WebSocketServer({server: server});  wss.on("connection", function(ws){    // ... }); 

I would like to put the WebSocketServer under a specific path which may for instance be "...com/whatever". The question is how can I set the path? Is it possible?

like image 365
0101 Avatar asked Mar 15 '14 21:03

0101


People also ask

How do I create a WebSocket server Express?

Creating a websocket server import express from "express"; import startup from "./lib/startup"; import api from "./api/index"; import middleware from "./middleware/index"; import logger from "./lib/logger"; import websockets from './websockets'; startup() . then(() => { const app = express(); const port = process. env.

Does express support WebSockets?

WebSocket endpoints for Express applications. Lets you define WebSocket endpoints like any other type of route, and applies regular Express middleware. The WebSocket support is implemented with the help of the ws library.

How do I run a WebSocket server?

To open a websocket connection, we need to create new WebSocket using the special protocol ws in the url: let socket = new WebSocket("ws://javascript.info"); There's also encrypted wss:// protocol. It's like HTTPS for websockets.

How do you set up a WebSocket protocol?

- In Control Panel, click Programs and Features, and then click Turn Windows features on or off. Expand Internet Information Services, expand World Wide Web Services, expand Application Development Features, and then select WebSocket Protocol. Click OK. Click Close.


2 Answers

You'll want to use the path option:

var wss = new WebSocketServer({server: server, path: "/hereIsWS"}); 

See full documentation here

like image 66
Aaron Dufour Avatar answered Oct 11 '22 14:10

Aaron Dufour


Use express-ws: https://www.npmjs.com/package/express-ws

Installation:

npm i express-ws -S 

HTTP server example:

const express = require('express') const enableWs = require('express-ws')  const app = express() enableWs(app)  app.ws('/echo', (ws, req) => {     ws.on('message', msg => {         ws.send(msg)     })      ws.on('close', () => {         console.log('WebSocket was closed')     }) })  app.listen(80) 

HTTPS server example:

NOTICE I strongly recommend making such features as HTTPS, compression and caching using an intermediate server between NodeJS and Internet, for example Nginx, it works much more efficiently and its configuration will be easier to change in the future

const https     = require('https') const fs        = require('fs') const express   = require('express') const expressWs = require('express-ws')  const serverOptions = {   key: fs.readFileSync('key.pem'),   cert: fs.readFileSync('cert.pem') }  const app       = express() const server    = https.createServer(serverOptions, app)  expressWs(app, server)  app.ws('/echo', (ws, req) => {     ws.on('message', msg => {         ws.send(msg)     })      ws.on('close', () => {         console.log('WebSocket was closed')     }) })  server.listen(443) 

Browser client example:

// wss: protocol is equivalent of https:  // ws:  protocol is equivalent of http: // You ALWAYS need to provide absolute address // I mean, you can't just use relative path like /echo const socketProtocol = (window.location.protocol === 'https:' ? 'wss:' : 'ws:') const echoSocketUrl = socketProtocol + '//' + window.location.hostname + '/echo/' const socket = new WebSocket(echoSocketUrl);  socket.onopen = () => {   socket.send('Here\'s some text that the server is urgently awaiting!');  }  socket.onmessage = e => {   console.log('Message from server:', event.data) } 
like image 28
ujeenator Avatar answered Oct 11 '22 16:10

ujeenator