Websockets: Difference between revisions

From bibbleWiki
Jump to navigation Jump to search
Line 1: Line 1:
=Simple JS example=
=Simple JS example=
==Client==
==Client==
<syntaxhighlight lang="js">
<syntaxhighlight lang="html">
<html>
<html>
     <body>
     <body>
Line 20: Line 20:
</html>
</html>
</syntaxhighlight>
</syntaxhighlight>
==Server==
==Server==
We need to npm install
We need to npm install

Revision as of 02:19, 31 July 2022

Simple JS example

Client

<html>
    <body>
        <script>
            const ws = new WebSocket("ws://localhost:3100")

            ws.addEventListener("open", () => {
                console.log("We are connected")
                ws.send("hello everyone")
            })

            ws.addEventListener("message", (e) => {
                console.log("We have data", e)
            })

        </script>
    </body>
</html>

Server

We need to npm install

  "dependencies": {
    "ws": "^8.8.1"
  }

And run this.

const Websocket  = require("ws")

const wss = new Websocket.Server({port: 3100})

wss.on("connection", ws => {

    console.log("New Client Connected")

    ws.on("message", (data) => {
        console.log("Client Sent", data)
        ws.send(data.toUpperCase())
    }) 

    ws.on("close", () => {
        console.log("Client Disconnected")
    })
})