new main project start
This commit is contained in:
37
crashsourceFiles/server.js
Normal file
37
crashsourceFiles/server.js
Normal file
@@ -0,0 +1,37 @@
|
||||
import {WebSocketServer, WebSocket} from 'ws'
|
||||
|
||||
const wss = new WebSocketServer({port: 8081})
|
||||
|
||||
// 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
|
||||
|
||||
s.on('message', (rawData)=>{
|
||||
const message = rawData.toString()
|
||||
console.log({rawData})
|
||||
|
||||
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