58 lines
1.3 KiB
JavaScript
58 lines
1.3 KiB
JavaScript
const {Board, Piece} = require('./src/backend');
|
|
|
|
const express = require("express");
|
|
const http = require("http");
|
|
const socketIo = require("socket.io");
|
|
|
|
const port = process.env.PORT || 4001;
|
|
|
|
const app = express();
|
|
|
|
const server = http.createServer(app);
|
|
|
|
const io = socketIo(server, {
|
|
cors: {
|
|
cors: true,
|
|
origins: ["http://192.168.1.7:3000"],
|
|
}
|
|
});
|
|
|
|
let interval;
|
|
|
|
let board = new Board();
|
|
|
|
let sockets = [];
|
|
|
|
io.on("connection", (socket) => {
|
|
sockets.push(socket);
|
|
console.log("New client connected");
|
|
if (interval) {
|
|
clearInterval(interval);
|
|
}
|
|
getApiAndEmit(socket);
|
|
//interval = setInterval(() => getApiAndEmit(socket), 5000);
|
|
socket.on("disconnect", () => {
|
|
// TODO sockets.remove(socket)
|
|
console.log("Client disconnected");
|
|
clearInterval(interval);
|
|
});
|
|
|
|
socket.on("move", (move) => {
|
|
console.log("Received move");
|
|
if(move && board.makeMove(move.from, move.to) == 0) {
|
|
for (s of sockets) {
|
|
getApiAndEmit(s);
|
|
}
|
|
}
|
|
});
|
|
});
|
|
|
|
const getApiAndEmit = socket => {
|
|
const response = board.textFromState();
|
|
console.log(response);
|
|
// Emitting a new message. Will be consumed by the client
|
|
socket.emit("FromAPI", response);
|
|
};
|
|
|
|
server.listen(port, () => console.log(`Listening on port ${port}`));
|