mirror of
https://github.com/thib8956/tic-tac-toe-ws.git
synced 2024-11-17 01:16:33 +00:00
33 lines
653 B
TypeScript
33 lines
653 B
TypeScript
import { WebSocketServer } from "ws";
|
|
|
|
const port = 1234
|
|
const wss = new WebSocketServer({ port });
|
|
|
|
console.log(`waiting for connection on ws://localhost:${port}`);
|
|
|
|
let id = -1;
|
|
let clients = [];
|
|
|
|
wss.on("connection", (ws, req) => {
|
|
id += 1;
|
|
if (id > 1) {
|
|
throw new Error("too many players");
|
|
}
|
|
|
|
clients.push(ws);
|
|
ws.send("bonjour" + id);
|
|
console.log(`player #${id} connected`);
|
|
|
|
ws.addEventListener("message", (event: any) => {
|
|
const message = event.data.toString();
|
|
console.log(`message from client : ${message}`);
|
|
if (id == 0) {
|
|
clients[1].send("coucou");
|
|
} else {
|
|
clients[0].send("coucou");
|
|
}
|
|
});
|
|
});
|
|
|
|
|