Last active
March 16, 2022 12:24
-
-
Save Drecu/2330024344404807600054425efefa36 to your computer and use it in GitHub Desktop.
WebSocket and Webserver on one Port implementation try
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import WebSocket from "ws"; | |
| import { createServer } from "http"; | |
| import express from "express"; | |
| import cors from "cors"; | |
| import compression from "compression"; | |
| // Description: | |
| // this code demonstrates the use of a HTTP server and WebSocket server on the same Port 8090! | |
| // Testing: | |
| // -------------------------------------------------------------------- | |
| // To test the Websocket: | |
| // connect to url ws://localhost:8090 and send payload websocketTest | |
| // ->should return succesfully processed websocket request | |
| // -------------------------------------------------------------------- | |
| // To test the Express Server | |
| // visit in browser the url http://localhost:8090/test | |
| // -> should return sucessful! | |
| // CONFIGS | |
| const WsAndExpressServerPort = 8090; | |
| let connectedClients = 0; | |
| // Express Server implementation: | |
| const expressServer = express(); | |
| expressServer.use(cors()); | |
| expressServer.use(compression()); | |
| // support json get & post and automatic parsing of headers and bodys. | |
| expressServer.use(express.json()); | |
| expressServer.use(express.urlencoded({ extended: true })); | |
| expressServer.use(express.text()); | |
| // Get requests | |
| expressServer.get("/test", (req, res) => { | |
| res.send("succesful get request with express"); | |
| }); | |
| const server = createServer(expressServer); | |
| // WebSocket Server implementation which uses Express server | |
| // (the websocket server will use the port from the passed server instance which you define in the variableWsAndHTTPServerPort) | |
| let wss = new WebSocket.Server({ | |
| server: server, | |
| }); | |
| wss.on("connection", function connection(ws) { | |
| connectedClients++; | |
| console.log("client connected to ws"); | |
| wss.clients.forEach(function each(_client) { | |
| console.log(`${connectedClients} Client${connectedClients > 1 ? "s" : ""} connected`); | |
| }); | |
| ws.on("message", function incoming(request) { | |
| console.log("received: %s", request); | |
| switch (request) { | |
| case "websocketTest": | |
| wss.clients.forEach(function each(client) { | |
| client.send("succesfully processed websocket request"); | |
| }); | |
| break; | |
| case "otherStuff": | |
| wss.clients.forEach(function each(client) { | |
| client.send("otherstuff"); | |
| }); | |
| break; | |
| default: | |
| wss.clients.forEach(function each(client) { | |
| client.send(`404 websocket request: ${request} does not exist`); | |
| }); | |
| break; | |
| } | |
| }); | |
| ws.on("error", function incoming(err) { | |
| console.log(`error received: ${err}`); | |
| }); | |
| ws.on("close", function close() { | |
| connectedClients--; | |
| console.log(`1 user disconnected. Current connected users: ${connectedClients}`); | |
| ws.send("Disconnecting connection"); | |
| }); | |
| }); | |
| // Start the server | |
| server.listen(WsAndExpressServerPort, function () { | |
| console.log(`Express and WebSocket server running on ${WsAndExpressServerPort}`); | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import WebSocket from "ws"; | |
| import { createServer } from "http"; | |
| // Description: | |
| // this code demonstrates the use of a HTTP server and WebSocket server on the same Port 8090! | |
| // Testing: | |
| // -------------------------------------------------------------------- | |
| // To test the Websocket: | |
| // connect to url ws://localhost:8090 and send payload websocketTest | |
| // ->should return succesfully processed websocket request | |
| // -------------------------------------------------------------------- | |
| // To test the HTTP Server | |
| // visit in browser the url http://localhost:8090/test | |
| // -> should return sucessful! | |
| // CONFIGS | |
| const WsAndHTTPServerPort = 8090; | |
| let connectedClients = 0; | |
| // HTTP Server implementation: | |
| const server = createServer(function (req, res) { | |
| if (req.method === "GET") { | |
| console.log("get request on: ", req.url); | |
| if (req.url === "/test") { | |
| res.writeHead(200, { "Content-Type": "text/html" }); | |
| res.write("succesfull rest get reqest"); | |
| res.end(); | |
| } else { | |
| res.writeHead(404, { "Content-Type": "text/html" }); | |
| res.write("Content does not exist on http server"); | |
| res.end(); | |
| } | |
| } else if (req.method === "POST") { | |
| // your post methods (i was to lazy to write a test here) | |
| } | |
| }); | |
| // WebSocket Server implementation which uses HTTP server | |
| // (the websocket server will use the port from the passed server instance which you define in the variable WsAndHTTPServerPort) | |
| let wss = new WebSocket.Server({ | |
| server: server, | |
| }); | |
| wss.on("connection", function connection(ws) { | |
| connectedClients++; | |
| console.log("client connected to ws"); | |
| wss.clients.forEach(function each(_client) { | |
| console.log(`${connectedClients} Client${connectedClients > 1 ? "s" : ""} connected`); | |
| }); | |
| ws.on("message", function incoming(request) { | |
| console.log("received: %s", request); | |
| switch (request) { | |
| case "websocketTest": | |
| wss.clients.forEach(function each(client) { | |
| client.send("succesfully processed websocket request"); | |
| }); | |
| break; | |
| case "otherStuff": | |
| wss.clients.forEach(function each(client) { | |
| client.send("otherstuff"); | |
| }); | |
| break; | |
| default: | |
| wss.clients.forEach(function each(client) { | |
| client.send(`404 websocket request: ${request} does not exist`); | |
| }); | |
| break; | |
| } | |
| }); | |
| ws.on("error", function incoming(err) { | |
| console.log(`error received: ${err}`); | |
| }); | |
| ws.on("close", function close() { | |
| connectedClients--; | |
| console.log(`1 user disconnected. Current connected users: ${connectedClients}`); | |
| ws.send("Disconnecting connection"); | |
| }); | |
| }); | |
| // Start the server | |
| server.listen(WsAndHTTPServerPort, function () { | |
| console.log(`HTTP and WebSocket server running on ${WsAndHTTPServerPort}`); | |
| }); |
Author
Thanks for the heads up @dagogodboss
i updated the code and cleaned it up.
And its also working this time. 🎉
The idea was to use express, why did you take out the express
Author
the first draft with the two seperate files didnt work so i used the more easy to use http package and omitted the server file.
Now i've also added an example with express.
(Just needed to switchout http server with express, everything else stays the same)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line 12 fails