js代码:
var socket = new WebSocket('ws://47.94.80.240:12345');
socket.onopen = function (evt) {
console.log("socket连接成功");
//提醒上线
var mes = {
type: 1
}
socket.send(JSON.stringify(mes));
};
部分php代码:
public function startServer()
{
// $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$this->master = socket_create_listen($this->port);
if (!$this->master) {
throw new \Exception('listen $this->port fail !');
}
$this->runLog("Server Started : " . date('Y-m-d H:i:s'));
$this->runLog("Listening on : 47.94.80.240 port " . $this->port);
$this->runLog("Master socket : " . $this->master . "\n");
self::$connectPool[] = $this->master;
while (true) {
$readFds = self::$connectPool;
//阻塞接收客户端链接
@socket_select($readFds, $writeFds, $e = ull, $this->timeout);
foreach ($readFds as $socket) {
//当前链接 是主进程
if ($this->master == $socket) {
$client = socket_accept($this->master); //接收新的链接
$this->handShake = false;
if ($client < 0) {
$this->log('clinet connect false!');
continue;
} else {
//超过最大连接数
if (count(self::$connectPool) > self::$maxConnectNum)
continue;
//加入连接池
$this->connect($client);
}
} else {
//不是主进程,开始接收数据
$bytes = @socket_recv($socket, $buffer, 2048, 0);
//未读取到数据
if ($bytes == 0) {
$this->disConnect($socket);
} else {
//未握手 先握手
if (!$this->handShake) {
$this->doHandShake($socket, $buffer);
} else {
//如果是已经握完手的数据,广播其发送的消息
$buffer = $this->decode($buffer);
$this->parseMessage($buffer, $socket);
}
}
}
}
}
}
socket 和 websocket 又不是一码事。
websocket 是更上层的协议,类比 http 协议。
我记得 websocket 连接的第一步是需要一个 http 请求。
具体我也忘记了。就是给个思路。你可以自己先研究一下他们的区别。