1
0
mirror of https://github.com/thib8956/tic-tac-toe-ws.git synced 2024-11-17 09:26:33 +00:00
tic-tac-toe-ws/server.mts

33 lines
653 B
TypeScript
Raw Normal View History

2024-09-02 20:34:24 +00:00
import { WebSocketServer } from "ws";
const port = 1234
const wss = new WebSocketServer({ port });
console.log(`waiting for connection on ws://localhost:${port}`);
2024-09-03 12:07:13 +00:00
let id = -1;
let clients = [];
2024-09-02 20:34:24 +00:00
wss.on("connection", (ws, req) => {
2024-09-03 12:07:13 +00:00
id += 1;
if (id > 1) {
throw new Error("too many players");
}
clients.push(ws);
ws.send("bonjour" + id);
console.log(`player #${id} connected`);
2024-09-02 20:34:24 +00:00
ws.addEventListener("message", (event: any) => {
const message = event.data.toString();
console.log(`message from client : ${message}`);
2024-09-03 12:07:13 +00:00
if (id == 0) {
clients[1].send("coucou");
} else {
clients[0].send("coucou");
}
2024-09-02 20:34:24 +00:00
});
});