typescriptexpresshttpwebsocketws

How can i run a server with websocket and http methods simultaneously ? (Typescript)


my question is the next... i want run a websocket server with the route like "ws://localhost:port" with the 'ws' library and it need the app instance of 'express' and also have http routes like this : "http://localhost:port/auth/login". I don't want the execution of one to freeze the execution of the other. the only "solution" i found is that one execute the other like a sub process with 'worker_threads' but this causes me a lots of problems like extensions or modules. if anyone can give a solution i will be really grateful

i tried execute this:

import WebSocket from "ws"
import indexRouter from "./routes/indexRouter" //a functionally routes of express 

const ws = new WebSocket.Server({server:createServer(express().use(indexRouter).listen(PORT)})

with this i can use ws and http but this can freeze with a complex http petition or many webSocket packages


Solution

  • If you don't want your webSocket code and your express code to be able to slow down the other (if one is running long running CPU-heavy code), then that means that they can't share the same nodejs engine.

    So, instead, you can put them in separate processes. To be able to share the same port, you would have to run them through a proxy like nginx that separates out the webSocket traffic from the plain http traffic and sends the webSocket traffic to your webSocket nodejs server (on it's own port) and sends the plain http traffic to your express nodejs server (on it's own port).

    The fact that your webSocket and Express servers were both running on different ports would not be visible to the outside world since the outside world would be just communicating with your nginx server on the one port.


    An alternative to splitting processes is to just make sure you don't run any CPU-heavy code in your main nodejs Javascript thread and use only asynchronous I/O and, in that way, keep both servers always responsive. If you have CPU-heavy operations, then you can shift them off to either a child_process or a WorkerThread.

    You can also cluster your server with the cluster module, giving it more CPUs to process requests.