Websockets: Difference between revisions

From bibbleWiki
Jump to navigation Jump to search
No edit summary
Line 1: Line 1:
=Pros and Cons=
=Pros and Cons=
```Pros```
'''Pros'''
*Full Duplex (no polling)
*Full Duplex (no polling)
*Http compatiable
*Http compatiable
*Firewall friendly
*Firewall friendly
```Cons```
'''Cons'''
*Proxy is tricky
*Proxy is tricky
*L7 Load Balancing challenging (timeouts)
*L7 Load Balancing challenging (timeouts)
*Stateful, difficult to horizontally scale
*Stateful, difficult to horizontally scale
=Simple JS example=
=Simple JS example=
==Client==
==Client==

Revision as of 02:52, 31 July 2022

Pros and Cons

Pros

  • Full Duplex (no polling)
  • Http compatiable
  • Firewall friendly

Cons

  • Proxy is tricky
  • L7 Load Balancing challenging (timeouts)
  • Stateful, difficult to horizontally scale

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")
    })
})