CrashCourse on basic ws
This commit is contained in:
29
server.js
29
server.js
@@ -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")
|
||||
Reference in New Issue
Block a user