如何向TCP服务器发送光标位置?PHP实现持续发送光标Cookie至C#服务器
Hey there! Let's fix this issue so your cursor position updates get sent to your C# TCP server consistently. The problem with your current Cookie approach is that Cookies only get sent to the server when the browser makes an HTTP request—just updating the Cookie doesn't trigger a request on its own.
Luckily, we can use a combination of frontend JavaScript (to track the cursor) and PHP (to forward the data to your TCP server) to make this work reliably. Here's a step-by-step solution:
Step 1: Update Frontend JS to Send Real-Time Cursor Data
Instead of storing coordinates in a Cookie, we'll use JavaScript to capture the cursor position and send it directly to a PHP endpoint via fetch. We'll add a debounce function to avoid flooding the server with too many requests:
<html> <script type="text/javascript"> let x, y; let debounceTimer; // Debounce function to limit request frequency (adjust delay as needed) function debounce(func, delay) { return function() { clearTimeout(debounceTimer); debounceTimer = setTimeout(func, delay); }; } window.onload = init; function init() { if (window.Event) { document.captureEvents(Event.MOUSEMOVE); } // Wrap the position handler in debounce to send updates every 100ms document.onmousemove = debounce(getCursorXY, 100); } function getCursorXY(e) { // Calculate cursor position (cross-browser compatible) x = window.Event ? e.pageX : event.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft); y = window.Event ? e.pageY : event.clientY + (document.documentElement.scrollTop || document.body.scrollTop); // Send coordinates to our PHP endpoint fetch('/send-cursor.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `x=${x}&y=${y}` }) .then(response => response.text()) .catch(error => console.error('Failed to send cursor data:', error)); } </script> <body> <!-- Your page content here --> </body> </html>
Step 2: Create the PHP Endpoint to Forward Data to TCP Server
This PHP script will receive the coordinates from the frontend, establish a TCP connection to your C# server, and send the data. Replace the server host and port with your actual C# server details:
<?php // Get cursor coordinates from frontend request $x = isset($_POST['x']) ? intval($_POST['x']) : 0; $y = isset($_POST['y']) ? intval($_POST['y']) : 0; // Configure your C# TCP server details $tcpServerHost = '127.0.0.1'; // Replace with your server IP $tcpServerPort = 8080; // Replace with your server port // Create TCP socket $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (!$socket) { error_log("Socket creation failed: " . socket_strerror(socket_last_error())); exit("Error connecting to server"); } // Connect to TCP server if (!socket_connect($socket, $tcpServerHost, $tcpServerPort)) { error_log("TCP connection failed: " . socket_strerror(socket_last_error($socket))); socket_close($socket); exit("Error connecting to server"); } // Format data (match this to your C# server's expected format) $data = "CursorPosition: {$x},{$y}\n"; // Send data to TCP server socket_write($socket, $data, strlen($data)); // Clean up connection socket_close($socket); // Confirm success to frontend echo "Cursor position sent!"; ?>
Key Notes to Make This Work
- Debounce Adjustment: The
100msdelay in the debounce function balances real-time updates and server load. If you need more frequent updates, lower the value (e.g., 50ms); if you want less traffic, raise it (e.g., 200ms). - PHP Socket Extension: Ensure the PHP
socketextension is enabled in yourphp.ini(look forextension=socketsand uncomment it if needed). - Data Format: The
$datavariable uses a simple string format—make sure your C# server is set up to parse this exact structure (adjust it if your server expects JSON or another format). - TCP Connection Handling: This example creates a new connection for each request. For higher performance, you could implement persistent connections, but this simple approach works for most use cases.
If you need even lower latency, consider using WebSockets instead (libraries like Ratchet for PHP can help with that), but the above solution is straightforward and should solve your immediate problem.
内容的提问来源于stack exchange,提问作者Sick Side

