beeter socket handle

This commit is contained in:
方而静 2023-07-05 13:58:52 +08:00
parent 1d25060d0e
commit 29eaa5c16e
3 changed files with 24 additions and 9 deletions

View File

@ -3,5 +3,5 @@ import { io } from "socket.io-client";
const socket = io(); const socket = io();
socket.on("update",(tank_info) => { socket.on("update",(tank_info) => {
document.querySelector("#raw-info").innerHTML = tank_info; document.querySelector("#raw-info").innerHTML = JSON.stringify(tank_info);
}); });

View File

@ -3,6 +3,7 @@
"version": "0.1.0", "version": "0.1.0",
"description": "", "description": "",
"source": "client/index.html", "source": "client/index.html",
"entry": "src/main.js",
"scripts": { "scripts": {
"test": "mocha tests/" "test": "mocha tests/"
}, },

View File

@ -5,17 +5,30 @@ import {Server} from 'socket.io';
import Express from 'express'; import Express from 'express';
import http_server from 'http'; import http_server from 'http';
import path from 'path'; import path from 'path';
import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = Express(); const app = Express();
const http = new http_server.Server(app); const http = new http_server.Server(app);
const io = new Server(http); const io = new Server(http);
const connections = new Set();
io.on("connection", (socket) => { io.on("connection", socket => {
connections.add(socket);
console.log(`Connected client ${socket.id}.`);
socket.on('time-sync', callback => {
callback(performance.now());
});
socket.on('disconnect', () => {
connections.delete(socket);
});
}); });
function main() { function main() {
app.use('/', Express.static(path.join('.','./dist'))); app.use('/', Express.static(path.join(__dirname, '../dist')));
const server_port = parseInt(process.env.PORT) | 3000; const server_port = parseInt(process.env.PORT) | 3000;
http.listen(server_port, () => { http.listen(server_port, () => {
@ -24,12 +37,13 @@ function main() {
process.on('SIGINT', () => { process.on('SIGINT', () => {
console.log('\nShutting server...'); console.log('\nShutting server...');
users.forEach(u => { connections.forEach(socket => {
u.socket.disconnect(); socket.disconnect();
console.log(`Disconnected user ${u.name}.`); console.log(`Disconnected socket ${socket.id};`);
}); })
http.close(() => { http.close(() => {
console.log('Closed.'); console.log('Terminated.');
process.exit(0); process.exit(0);
}); });
}); });
@ -46,7 +60,7 @@ function main() {
}, 1000/60); }, 1000/60);
setInterval(() => { setInterval(() => {
io.emit("update",JSON.stringify(registry.get(tank, Motion))) io.emit("update", registry.get(tank, Motion))
}, 50); }, 50);
} }