這篇文章主要介紹了php使用websocket示例,需要的朋友可以參考下
下面我畫了一個圖演示 client 和 server 之間建立 websocket 連接時握手部分,這個部分在 node 中可以十分輕松的完成,因為 node 提供的 net 模塊已經(jīng)對 socket 套接字做了封裝處理,開發(fā)者使用的時候只需要考慮數(shù)據(jù)的交互而不用處理連接的建立。而 php 沒有,從 socket 的連接、建立、綁定、監(jiān)聽等,這些都需要我們自己去操作,所以有必要拿出來再說一說。
① 和 ② 實際上就是一個 HTTP 的請求和響應(yīng),只不過我們在處理的過程中我們拿到的是沒有經(jīng)過解析的字符串。如:
復(fù)制代碼 代碼如下:
GET /chat HTTP/1.1
Host: server.example.com
Origin:
我們往??吹降恼埱笫沁@個樣子,當(dāng)這東西到了服務(wù)器端,我們可以通過一些代碼庫直接拿到這些信息。
一、php 中處理 websocket
WebSocket 連接是由客戶端主動發(fā)起的,所以一切要從客戶端出發(fā)。第一步是要解析拿到客戶端發(fā)過來的 Sec-WebSocket-Key 字符串。
復(fù)制代碼 代碼如下:
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin:
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
client 請求的格式
首先 php 建立一個 socket 連接,監(jiān)聽端口的信息。
1. socket 連接的建立
關(guān)于 socket 套接字的建立,相信很多大學(xué)修過計算機網(wǎng)絡(luò)的人都知道了,下面是一張連接建立的過程:
復(fù)制代碼 代碼如下:
// 建立一個 socket 套接字
$master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($master, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($master, $address, $port);
socket_listen($master);
相比 node,這個地方的處理實在是太麻煩了,上面幾行代碼并未建立連接,只不過這些代碼是建立一個 socket 套接字必須要寫的東西。由于處理過程稍微有復(fù)雜,所以我把各種處理寫進了一個類中,方便管理和調(diào)用。
復(fù)制代碼 代碼如下:
//demo.php
Class WS {
??? var $master;? // 連接 server 的 client
??? var $sockets = array(); // 不同狀態(tài)的 socket 管理
??? var $handshake = false; // 判斷是否握手
??? function __construct($address, $port){
??????? // 建立一個 socket 套接字
??????? $this->master = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)??
??????????? or die("socket_create() failed");
??????? socket_set_option($this->master, SOL_SOCKET, SO_REUSEADDR, 1)?
??????????? or die("socket_option() failed");
??????? socket_bind($this->master, $address, $port)???????????????????
??????????? or die("socket_bind() failed");
??????? socket_listen($this->master, 2)??????????????????????????????
??????????? or die("socket_listen() failed");
??????? $this->sockets[] = $this->master;
??????? // debug
??????? echo("Master socket? : ".$this->master."\n");
??????? while(true) {
??????????? //自動選擇來消息的 socket 如果是握手 自動選擇主機
??????????? $write = NULL;
??????????? $except = NULL;
??????????? socket_select($this->sockets, $write, $except, NULL);
??????????? foreach ($this->sockets as $socket) {
??????????????? //連接主機的 client
??????????????? if ($socket == $this->master){
??????????????????? $client = socket_accept($this->master);
??????????????????? if ($client < 0) {
// debug
echo "socket_accept() failed";
continue;
} else {
//connect($client);
array_push($this->sockets, $client);
??????????????????????? echo "connect client\n";
??????????????????? }
??????????????? } else {
??????????????????? $bytes = @socket_recv($socket,$buffer,2048,0);
??????????????????? if($bytes == 0) return;
??????????????????? if (!$this->handshake) {
??????????????????????? // 如果沒有握手,先握手回應(yīng)
??????????????????????? //doHandShake($socket, $buffer);
??????????????????????? echo "shakeHands\n";
??????????????????? } else {
??????????????????????? // 如果已經(jīng)握手,直接接受數(shù)據(jù),并處理
??????????????????????? $buffer = decode($buffer);
??????????????????????? //process($socket, $buffer);
??????????????????????? echo "send file\n";
??????????????????? }
??????????????? }
??????????? }
??????? }
??? }
}
上面這段代碼是經(jīng)過我調(diào)試了的,沒太大的問題,如果想測試的話,可以在 cmd 命令行中鍵入 php /path/to/demo.php;當(dāng)然,上面只是一個類,如果要測試的話,還得新建一個實例。
復(fù)制代碼 代碼如下:
$ws = new WS('localhost', 4000);
客戶端代碼可以稍微簡單點:
復(fù)制代碼 代碼如下:

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Xiaomi car software provides remote car control functions, allowing users to remotely control the vehicle through mobile phones or computers, such as opening and closing the vehicle's doors and windows, starting the engine, controlling the vehicle's air conditioner and audio, etc. The following is the use and content of this software, let's learn about it together . Comprehensive list of Xiaomi Auto app functions and usage methods 1. The Xiaomi Auto app was launched on the Apple AppStore on March 25, and can now be downloaded from the app store on Android phones; Car purchase: Learn about the core highlights and technical parameters of Xiaomi Auto, and make an appointment for a test drive. Configure and order your Xiaomi car, and support online processing of car pickup to-do items. 3. Community: Understand Xiaomi Auto brand information, exchange car experience, and share wonderful car life; 4. Car control: The mobile phone is the remote control, remote control, real-time security, easy
