Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How to create a Websocket server

Lloyd Brookes edited this pageJul 6, 2021 ·4 revisions

The easiest way to handle Websocket requests is to use thewebsockets/ws module in a middleware plugin.

  1. Install thewebsocket/ws module.

    $ npm install --save-dev ws
  2. Create a middleware plugin. Save the following example code aswebsocket.js. This plugin delegates Websocket request handling to the websocket module by passing inlws.server. If a Websocket request comes in, it will be handled by this plugin else passed to the next middleware plugin in the stack.

    classWebsocket{middleware(config,lws){constWebSocket=require('ws')constwss=newWebSocket.Server({server:lws.server})wss.on('connection',socket=>{socket.on('message',message=>{console.log(`Received:${message}`)constreply="Wow, that's great"console.log(`Sending:${reply}`)socket.send(reply)})})}}exportdefaultWebsocket
  3. Now we need a client to test our server. Save this asindex.html.

    <!DOCTYPE html><html><head><title>Websocket example</title></head><body><h1>Websocket example</h1><p><button>Send message</button></p><pre><code></code></pre><script>constsocket=newWebSocket('ws://localhost:8000')const$=document.querySelector.bind(document)functionsendMessage(msg){$('code').innerHTML+=`Sending:${msg}\n`socket.send(msg)}socket.addEventListener('open',()=>{sendMessage('Hello from the client')})socket.addEventListener('message',event=>{$('code').innerHTML+=`Received:${event.data}\n`})$('button').addEventListener('click',e=>{sendMessage('Client clicked the button')})</script></body></html>
  4. Launch the server using our Websocket plugin pluslws-static to handle requests for static assets (e.g.index.html).

    $ ws --stack websocket.js lws-staticListening on http://mba4.local:8000, http://127.0.0.1:8000, http://192.168.0.200:8000
  5. Finally, open your browser, navigate tohttp://127.0.0.1:8000 and click the button. On the client, you should see this output:

    Sending: Hello from the clientReceived: Wow, that's greatSending: Client clicked the buttonReceived: Wow, that's great

    And the output from the server should look like this:

    Received: Hello from the clientSending: Wow, that's greatReceived: Client clicked the buttonSending: Wow, that's great

See also

Clone this wiki locally


[8]ページ先頭

©2009-2025 Movatter.jp