KF-MMO-Server/index.ts

69 lines
1.7 KiB
TypeScript
Raw Normal View History

2023-09-14 16:59:21 +08:00
import { registerAccountCallbacks } from "./Account/accountSocket";
import { users } from "./Account/users";
import { registerLobbyCallbacks } from "./Lobby/lobbySocket";
import { playerData } from "./Player/playerData";
import { game } from "./game";
const express = require("express");
const app = express();
const port = 3000;
const server = require('http').Server(app);
server.listen(port, () => {
console.log(`Server listening at port ${port}`);
});
const io = require("socket.io")(server, {
cors: {
origin: '*',
methods: ["GET", "POST"]
}
});
users.loadUsers();
io.on('connection', (socket) => {
console.log("Got connection!");
socket.emit("connectSuccess", "");
2023-09-15 04:49:31 +08:00
2023-09-14 16:59:21 +08:00
registerAccountCallbacks(socket);
registerLobbyCallbacks(socket);
socket.io = io;
socket.on("disconnect", () => {
socket.disconnect()
2023-09-15 04:49:31 +08:00
let idx = game.lobbyState.players.findIndex((pl) => pl.socketId == socket.id)
if(idx != -1){
game.lobbyState.players.splice(idx, 1)
}
delete socket.userId
console.log(socket.id + " disconnected");
2023-09-14 16:59:21 +08:00
});
socket.on('error',function(er){
console.log(er);
});
});
2023-09-15 04:49:31 +08:00
//Send player updates to everyone
2023-09-14 16:59:21 +08:00
setInterval(() => {
2023-09-15 04:49:31 +08:00
let userCount = game.lobbyState.players.length
2023-09-14 16:59:21 +08:00
if(userCount > 0){
2023-09-15 04:49:31 +08:00
game.lobbyState.hostSocket = game.lobbyState.players[0].socketId
io.emit('lobby', JSON.stringify(game.lobbyState))
2023-09-14 16:59:21 +08:00
}
}, 1000/30)
setInterval(() => {
2023-09-15 04:49:31 +08:00
console.log("Connected losers: " + game.lobbyState.players.length);
2023-09-14 16:59:21 +08:00
}, 60 * 1000)
process.on('SIGINT', function () {
console.log('Ctrl-C...');
process.exit(2);
});
process.on('exit', function () {
users.saveUsers();
console.log("exitted");
});