CrashCourse on basic ws

This commit is contained in:
2026-01-31 07:04:01 -06:00
parent 9eb51b7e9f
commit e3f990815b
4 changed files with 199 additions and 10 deletions

View File

@@ -1,8 +1,16 @@
import {WebSocketServer} from 'ws'
import {WebSocketServer, WebSocket} from 'ws'
const wss = new WebSocketServer({port: 8081})
// conmnection event
// connection event
/**
* Connection types
* 0: connecting
* 1: open (the only state where you can safely .send())
* 2: Closing
* 3: closed
*/
wss.on('connection', (s, r)=>{
const ip = r.socket.remoteAddress
@@ -11,8 +19,19 @@ wss.on('connection', (s, r)=>{
const message = rawData.toString()
console.log({rawData})
wss.clients.forEach((c)=>{
if(c.readyState === 1) c.send(`Server Broadcast: ${message}`)
wss.clients.forEach((client)=>{
// can use readyState to be === 1 or WebSocket.OPEN they mean the same thing
if(client.readyState === WebSocket.OPEN) client.send(`Server Broadcast: ${message}`)
})
})
})
s.on("error", ()=>{
console.error(`Error: ${err.message}: ${ip}`)
})
s.on('close', ()=>{
console.log('Client Disconnected')
})
})
console.log("Server Running on 8081")