-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
48 lines (41 loc) · 1.59 KB
/
Copy pathserver.js
File metadata and controls
48 lines (41 loc) · 1.59 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
const os = require('os');
const WebSocket = require('ws');
// 定義一個函數來獲取本機的 IPv4 地址
function getLocalIPAddress() {
// const interfaces = os.networkInterfaces();
// for (const name of Object.keys(interfaces)) {
// for (const iface of interfaces[name]) {
// // 忽略 IPv6 和內部地址(127.0.0.1)
// if (iface.family === 'IPv4' && !iface.internal) {
// return iface.address;
// }
// }
// }
return '192.168.1.123'; // 如果沒有找到非內部的 IPv4,返回localhost
}
const serverIP = getLocalIPAddress();
// 創建 WebSocket 伺服器,綁定到自動獲取的 IP 和端口上
const wss = new WebSocket.Server({host: serverIP, port: 8080});
wss.on('connection', function connection(ws) {
console.log('A new client connected');
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
if (client === ws) {
client.send(JSON.stringify({"type": 1, "PlayerCount": wss.clients.size-1}));
} else {
client.send('OnNewPlayerJoin');
}
}
});
ws.on('message', function incoming(message) {
console.log('received: %s', message);
// 廣播訊息給所有已連接的客戶端
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send('' + message);
console.log('send: %s', message);
}
});
});
});
console.log(`WebSocket server is running on ws://${serverIP}:8080`);