Build Real-Time PHP Apps with PHPSocket.IO: A Quick Start Guide
PHPSocket.IO is a PHP implementation of the Socket.IO server that offers full compatibility with v1.3‑v2.x clients, automatic fallback to long‑polling, and seamless integration with PHP frameworks, and this guide walks you through its core features, differences, installation, and sample server‑client code.
Overview
PHPSocket.IO is a PHP implementation of the Socket.IO server, created by the Workerman author walkor. It allows PHP developers to build real‑time applications without switching to Node.js while remaining fully compatible with Socket.IO client protocols (v1.3.0 ~ v2.x).
Core Features
Preferentially uses the WebSocket protocol for efficient, low‑latency communication.
If WebSocket is unavailable, it automatically falls back to HTTP long‑polling, JSONP polling, or Adobe Flash Socket.
The fallback process is transparent to developers; the same Socket.IO API is used throughout.
Design Goals
Enable cross‑browser, cross‑device real‑time applications such as online chat rooms, customer‑service systems, comment/danmaku systems, WebIM, and real‑time dashboards.
Leverage the PHP ecosystem; integration with frameworks like Webman, ThinkPHP, and Laravel is straightforward.
Differences from Workerman
PHPSocket.IO is built on top of Workerman, inheriting its high‑performance asynchronous, non‑blocking, multi‑process characteristics.
Its main advantage is better browser compatibility thanks to a more complete fallback mechanism, while Workerman itself is a lower‑level library supporting TCP/UDP/HTTP/WebSocket and other protocols.
Differences from Node.js Socket.IO
The official Socket.IO server is written in Node.js and relies on libuv for its event loop.
PHPSocket.IO is written in PHP, using Workerman’s event loop (based on libevent or select/epoll).
In high‑concurrency scenarios the Node.js version generally outperforms the PHP version, but PHPSocket.IO is sufficient for small‑to‑medium real‑time applications and benefits from familiar PHP deployment.
Quick Start
Installation
composer require workerman/phpsocket.ioServer Code (PHP)
<?php
namespace app\http\controller;
use PHPSocketIO\SocketIO;
use think\facade\Log;
use Workerman\Worker;
class Server {
public function server() {
// Track online connections per uid (supports multi‑device login)
$uidConnectionMap = [];
$last_online_count = 0;
$last_online_page_count = 0;
// Create PHPSocketIO service listening on port 2120 (WebSocket primary port)
$sender_io = new SocketIO(2120);
// ------------------- client connection event -------------------
$sender_io->on('connection', function($socket) {
Log::info('客户端发起连接');
// ------------------- login event -------------------
$socket->on('login', function($uid) use ($socket) {
Log::info("客户端登录 uid: {$uid}");
global $uidConnectionMap;
if (isset($socket->uid)) {
return;
}
$uid = (string) $uid;
if (!isset($uidConnectionMap[$uid])) {
$uidConnectionMap[$uid] = 0;
}
++$uidConnectionMap[$uid];
$socket->join($uid);
$socket->uid = $uid;
});
// ------------------- disconnect event -------------------
$socket->on('disconnect', function() use ($socket) {
Log::info('客户端断开: ' . json_encode($socket));
if (!isset($socket->uid)) {
return;
}
global $uidConnectionMap;
if (--$uidConnectionMap[$socket->uid] <= 0) {
unset($uidConnectionMap[$socket->uid]);
}
});
});
// ------------------- HTTP push interface (after workers start) -------------------
$sender_io->on('workerStart', function() use ($sender_io) {
// HTTP worker listening on 2121 for internal push requests
$inner_http_worker = new Worker('http://0.0.0.0:2121');
$inner_http_worker->onMessage = function($http_connection, $data) use ($sender_io) {
$postData = $data['post'] ?? [];
$to = $postData['to'] ?? '';
$content = htmlspecialchars($postData['content'] ?? '', ENT_QUOTES, 'UTF-8');
Log::info('推送目标: ' . json_encode($to));
if ($to) {
// Targeted push to a specific uid (room)
$sender_io->to($to)->emit('new_msg', $content);
} else {
// Broadcast to all connections
$sender_io->emit('new_msg', $content);
}
// Return push result (offline user returns 'offline')
if ($to && !isset($uidConnectionMap[$to])) {
$http_connection->send('offline');
} else {
$http_connection->send('ok');
}
};
$inner_http_worker->listen();
});
// Start all workers (SocketIO + HTTP worker)
Worker::runAll();
}
}Start Command
php web_msg.php start -dSample Daemon Output
Workerman[web_msg.php] start in DAEMON mode
──────────────────────────────────────────── WORKERMAN ────────────────────────────────────────────
Workerman version: 5.1.2 PHP version: 8.2.19
───────────────────────────────────────────── WORKERS ─────────────────────────────────────────────
proto user worker listen processes status
───── ──── ────────── ──────────────────────── ───────── ──────
tcp www PHPSocketIO socketIO://0.0.0.0:2120 1 [OK]Message Push Function (PHP)
/**
* Push a message to PHPSocket.IO with error handling
*/
function send_web_msg($to_uid = 1, string $content = ''): string|array {
if (empty($content)) {
return ['error_code' => 404, 'reason' => '缺少推送内容'];
}
$url = 'http://127.0.0.1:2121/';
$data = [
'type' => 'publish',
'content' => $content,
'to' => (string) $to_uid,
];
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($data),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 5,
CURLOPT_CONNECTTIMEOUT => 2,
CURLOPT_HTTPHEADER => ['Expect:'],
]);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch) || $http_code !== 200) {
$error = curl_error($ch) ?: "HTTP {$http_code}";
curl_close($ch);
return ['error_code' => 500, 'reason' => "推送失败:{$error}"];
}
curl_close($ch);
return trim($response) ?: 'ok';
}Client Code (JavaScript)
// Socket.IO client initialization script
// - Connect to server
// - Login with uid
// - Listen for new_msg events and display notifications
$(document).ready(function() {
const uid = "1"; // Ideally injected from backend or localStorage
const socket = io("https://www.tinywan.com", {
path: "/socket.io",
transports: ["websocket", "polling"],
reconnection: true,
reconnectionAttempts: 5,
timeout: 10000
});
socket.on("connect", function() {
console.log("Socket.IO 连接成功");
socket.emit("login", uid);
});
socket.on("connect_error", function(err) {
console.error("Socket.IO 连接失败:", err.message);
});
socket.on("new_msg", function(msg) {
console.log("收到系统消息:", msg);
$("#notice-content").html(`系统提示:${msg}`);
$(".notification.sticky").notify({
className: "info",
autoHide: true,
clickToHide: true,
position: "top right",
hideDuration: 3000
});
});
});This guide demonstrates how PHPSocket.IO provides a PHP‑centric real‑time communication solution, outlines its fallback mechanisms, compares it with the original Node.js implementation, and supplies complete server‑side and client‑side code to get a functional chat‑style application up and running.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
