-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
69 lines (59 loc) · 2.57 KB
/
Copy pathserver.js
File metadata and controls
69 lines (59 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
const WebSocket = require('ws')
const http = require('http')
const fs = require('fs')
const path = require('path')
const PORT = 8089
const HTML_PATH = path.join(__dirname, 'index.html')
// --- WebSocket Server ---
const wss = new WebSocket.Server({ noServer: true })
wss.on('connection', (ws) => {
const id = Date.now()
console.log(`[Server] Client connected: ${id}`)
ws.on('message', (data) => {
let msg
try { msg = JSON.parse(data.toString()) } catch { msg = { raw: data.toString() } }
console.log(`[Server] Received from ${id}:`, JSON.stringify(msg))
if (msg.token || msg.auth) {
ws.send(JSON.stringify({ code: 1, type: 'auth_success', Header: { MsgType: 92 }, data: { clientId: id } }))
return
}
if (msg.type === 'ping' || msg.heartbeat) {
ws.send(JSON.stringify({ code: 1, type: 'pong', Header: { MsgType: 91 }, data: { timestamp: Date.now() } }))
return
}
if (msg.action === 'subscribe') {
const key = `sub_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`
ws.send(JSON.stringify({ code: 1, type: 'subscribe_success', Header: { MsgType: 95 }, data: { key, body: msg.data || msg } }))
setTimeout(() => {
ws.send(JSON.stringify({ code: 100, type: 'quote_push', Header: { MsgType: 100 }, data: { stock: (msg.data || msg).stock || 'TEST', price: (Math.random() * 100 + 10).toFixed(2), time: new Date().toISOString() } }))
}, 500)
return
}
if (msg.action === 'unsubscribe') {
ws.send(JSON.stringify({ code: 1, type: 'unsubscribe_success', data: { body: msg.data || msg } }))
return
}
ws.send(JSON.stringify({ code: 1, type: 'echo', data: { echo: msg, from: id } }))
})
ws.on('close', () => console.log(`[Server] Client disconnected: ${id}`))
ws.on('error', (err) => console.error(`[Server] Error ${id}:`, err.message))
})
// --- HTTP Server (shared with WebSocket) ---
const server = http.createServer((req, res) => {
fs.readFile(HTML_PATH, 'utf-8', (err, data) => {
if (err) { res.writeHead(500); res.end('Internal Server Error'); return }
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })
res.end(data)
})
})
server.on('upgrade', (req, socket, head) => {
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit('connection', ws, req)
})
})
server.listen(PORT, '0.0.0.0', () => {
console.log(`HTTP server: http://localhost:${PORT}`)
console.log(`WebSocket server: ws://localhost:${PORT}`)
console.log(`\nOpen http://localhost:${PORT} in your browser\n`)
})
process.on('SIGINT', () => { wss.close(); server.close(); process.exit(0) })