Skip to content

Instantly share code, notes, and snippets.

@mattische
Created February 18, 2026 13:59
Show Gist options
  • Select an option

  • Save mattische/41aad804dd607e6325285bd90c6d8574 to your computer and use it in GitHub Desktop.

Select an option

Save mattische/41aad804dd607e6325285bd90c6d8574 to your computer and use it in GitHub Desktop.

Exempel från föreläsning 260218

i node finns inte native api:t - behöver installeras:

npm install ws

server.js

import { WebSocketServer } from "ws";

const PORT = 8181

const wss = new WebSocketServer({ port: PORT })

const clients = new Map()

wss.on("connection", (ws) => {
    clients.set(ws, { name: null })

    console.log("Client connected")

    ws.on("message", (data) => {
        const msg = JSON.parse(data.toString())

        switch (msg.type) {
            case "join": {
                clients.get(ws).name = msg.name
                console.log(`${msg.name} connected (tot ${clients.size})`)
                ws.send(JSON.stringify({ type: "welcome", name: msg.name }))
                broadcast(ws, { type: "info", message: `${msg.name} joined`})
                break
            }
            case "message": {
                const { name } = clients.get(ws)
                broadcast(ws, { type: "message", from: name, text: msg.text })
                break
            }
        }

    })

    function broadcast(sender, data) {
        const json = JSON.stringify(data)
        for(const [client] of clients) {
            if(client !== sender && client.readyState === client.OPEN) {
                client.send(json)
            }
        }
    }

    ws.on("close", () => {
        const { name } = clients.get(ws)
        clients.delete(ws)
        if(name) {
            console.log(`${name} disconnected (tot ${clients.size})`)
            broadcast(null, { type: "info", message: `${name} left`})
        }
    })
})

console.log(`Server started on port ${PORT}`)

client.js

import WebSocket from "ws"
import readline from "readline"

const ws = new WebSocket("ws://localhost:8181")

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
})

rl.on("line", (line) => {
    if(line.trim()) {
        ws.send(JSON.stringify({ type: "message", text: line.trim() }))
    }
})

ws.on("open", () => {
    rl.question("Your name: ", (name) => {
        if(name)
            ws.send(JSON.stringify( { type: "join", name: name.trim() } ))
    })
})

ws.on("message", (data) => {
    const msg = JSON.parse(data.toString())
    
    switch (msg.type) {
        case "welcome":
            console.log(`\nWelcome ${msg.name}! Type a message and press enter.\n`)
            break
        case "info":
            console.log(`--- ${msg.message} ---`)
            break
        case "message":
            console.log(`${msg.from}: ${msg.text}`)
            break
    }
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment