Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file removed .DS_Store
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { environment } from "../../../../environments/environment";
import { useEffect, useRef } from "react";
import io from "socket.io-client";

export function useSocketChessEngine(onEvaluationComplete: (data: any) => void) {
const socketRef = useRef<any>(null);

useEffect(() => {
const socket = io("http://localhost:8080", { transports: ["websocket"] });
const socket = io(environment.urls.stockFishURL, { transports: ["websocket"] });
socketRef.current = socket;

socket.on("connect", () => {
Expand Down
6 changes: 3 additions & 3 deletions stockfishServer/StockfishManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ let enginePath;

switch (process.platform) {
case 'win32':
enginePath = "./bin/stockfish.exe";
enginePath = "./bin/stockfish_11_win.exe";
break;
case 'darwin':
enginePath = "./bin/stockfish-macos";
enginePath = "./bin/stockfish_11_mac";
break;
case 'linux':
enginePath = "./bin/stockfish-ubuntu";
enginePath = "./bin/stockfish_11_linux";
break;
default:
throw new Error(`Unsupported platform: ${process.platform}`);
Expand Down
Empty file modified stockfishServer/bin/stockfish_11_linux
100644 → 100755
Empty file.
Empty file modified stockfishServer/bin/stockfish_11_mac
100644 → 100755
Empty file.
113 changes: 34 additions & 79 deletions stockfishServer/index.js
Original file line number Diff line number Diff line change
@@ -1,88 +1,43 @@
require("dotenv").config();

const express = require("express");
const http = require("http");
const socketIo = require("socket.io");
const cors = require("cors");
const rateLimit = require("express-rate-limit");
const { Chess } = require("chess.js");
const Stockfish = require("stockfish");
const querystring = require("querystring");
const url = require("url");
const { SSL_OP_SSLEAY_080_CLIENT_DH_BUG } = require("constants");

const app = express();
// Import the socket handlers that use StockfishManager
const initializeSocket = require("./socket");

// Set rate limit - 30 requests/minute per IP
const limiter = rateLimit({
windowMs: 60 * 1000,
max: 30,
message: { error: "Too many requests! Please try again." },
const app = express();
const server = http.createServer(app);

// Socket.io with CORS
const io = socketIo(server, {
cors: {
origin: "*",
methods: ["GET", "POST"],
},
});
app.use(limiter);

// CORS headers
app.use((req, res, next) => {
// WARNING: allow only selected access for production
res.setHeader("Access-Control-Allow-Origin", "*");

res.setHeader("Content-Type", "application/json");
next();
// Middleware
app.use(cors());
app.use(express.json());
app.use(
rateLimit({
windowMs: 60 * 1000, // 1 minute
max: 30,
message: { error: "Too many requests!" },
})
);

app.get("/health", (req, res) => res.json({ status: "OK" }));

// Socket.io connection handling
io.on("connection", (socket) => {
console.log(`New client (${socket.id}) connected!`);
initializeSocket(io, socket); // StockfishManager handles all session events
});

// Main API route
app.get("/", (req, res) => {
const params = querystring.parse(url.parse(req.url, true).search?.substring(1));
const { fen, move = "", level = 10, info = false } = params;

// Validate input
if (!fen || isNaN(level)) {
return res.status(400).json({ error: "Missing or invalid parameters!" });
}

const maxLevel = 30;
var lines = [];
var depth = Math.min(parseInt(level), maxLevel);
const engine = Stockfish();

const game = new Chess(fen);

engine.onmessage = (line) => {
if (info) {

lines.push(line);
if (line.startsWith("bestmove")) {
res.json({ output: lines });
}
}
else if (line.startsWith("bestmove")) {
const moveResult = game.move(line.split(" ")[1], { sloppy: true });

if (moveResult) {
const color = moveResult.color;
const piece = moveResult.piece.toUpperCase();
const move = color + piece;
const target = moveResult.to;
res.end(`${game.fen()} move:${move} target:${target}`);
}
else {
res.end("Invalid move or game state");
}
}
}

// Send position + evaluation command to the engine
engine.postMessage(`position fen ${fen} moves ${move}`);
engine.postMessage(`go depth ${depth}`);

// Set timeout for safety
setTimeout(() => {
if (!res.writableEnded) {
res.status(504).json({ error: "Engine timeout!" });
}
}, 5000);
});


// Start the server
const PORT = process.env.PORT || 5001;
app.listen(PORT, () => {
console.log(`Stockfish server running on port ${PORT}`);
});
// Start server
const PORT = process.env.PORT || 8080;
server.listen(PORT, () => console.log(`Stockfish server running on port ${PORT}`));
35 changes: 0 additions & 35 deletions stockfishServer/index_new.js

This file was deleted.

139 changes: 0 additions & 139 deletions stockfishServer/index_refactor.js

This file was deleted.