Implementing PHP and websocket chat room based on Swoole_php example

WBOY
Release: 2016-08-17 13:02:31
Original
999 people have browsed it

websocket

Websocket is just a network communication protocol

Just like http, ftp, etc. are all network communication protocols; don’t think too much;

Compared to non-persistent protocols like HTTP, Websocket is a protocol for persistent network communication;

The relationship between WebSocket and HTTP

There is intersection, but not all.

Websocket just borrows part of the HTTP protocol to complete a handshake. (HTTP’s three-way handshake is only completed once here)

Comparison of http and websocket request headers:


HTTP:

Originally, the client requested the server with a letter through http (horseback riding), the server processed the request (wrote a reply), and returned again through http (horseback riding); the link was broken;

WebSocket:

The client requests the server with a letter through http (horseback), but at the same time, it carries Upgrade: websocket and Connection: Upgrade (two pipes). If the server supports the WebSocket protocol (an interface with two pipes) , using the Websocket protocol to return available information (discarding the horse). Afterwards, the transmission of information will use these two pipes, unless one party artificially cuts off the pipe; if the server does not support it, the client fails to request the link and returns an error message;

Comparison of http and websocket response headers:


The difference between websocket, ajax polling and long poll

The first is ajax polling. The principle of ajax polling is very simple. It allows the browser to send a request every few seconds to ask the server if there is new information

Scene reproduction:

Client: La la la, is there any new information (Request)

Server: No (Response)

Client: La la la, is there any new information (Request)

Server: None. . (Response)

Client: La la la, is there any new information (Request)

Server: You are so annoyed, no. . (Response)

Client: La la la, is there any new message (Request)

Server: Okay, okay, here it is for you. (Response)

Client: La la la, is there any new message (Request)

Server:. . . without. . . . without. . No

long poll In fact, the principle is similar to ajaxpolling. They both use polling and will not be discussed here;

As can be seen from the above, polling is actually continuously establishing HTTP connections and then waiting for the server to process, which can reflect another characteristic of the HTTP protocol, passivity. At the same time, after each http request and response, the server discards all client information. The next request must carry identity information (cookie), stateless;

The emergence of Websocket has neatly solved these problems;

So the above scenario can be modified as follows.

Client: La la la, I want to establish the Websocket protocol, the required service: chat, Websocket protocol version: 17 (HTTP Request)

Server: ok, confirmed, has been upgraded to Websocket protocol (HTTP Protocols Switched)

Client: Please push it to me when you have information. .

Server: ok, I will tell you sometimes.

Client: balab starts fighting with alabala

Server: Sora Aoi

Client: I have a nosebleed, let me wipe it...

Server: Hahabul Education is awesome hahahaha

Server: I’m laughing so hard haha

Swoole

However, in order to use PHP and HTML5 to complete a WebSocket request and response, I traveled thousands of miles and found Swoole deep in the jungle:

PHP language’s asynchronous, parallel, high-performance network communication framework, written in pure C language, provides PHP language’s asynchronous multi-threaded server, asynchronous TCP/UDP network client, asynchronous MySQL, database connection pool, AsyncTask, message queue, Millisecond timer, asynchronous file reading and writing, asynchronous DNS query.

Supported services:

HttpServer

WebSocket Server

TCP Server

TCP Client

Async-IO(asynchronous)

Task(scheduled task)

Environment dependencies:

Only supports Linux, FreeBSD, MacOS, type 3 operating systems

Linux kernel version 2.3.32 or above

PHP5.3.10 or above

gcc4.4 or above version or clang

cmake2.4+, you need to use cmake when compiling to libswoole.so as a C/C++ library

Installation:

You must ensure that the following software is present in the system:

php-5.3.10 or higher

gcc-4.4 or higher

make

autoconf

Swoole runs as a PHP extension

Installation (root permission):

cd swoole

phpize

./configure

make

sudo make install

Configure php.ini

extension=swoole.so

For those who want to study Swoole, read the manual yourself (although it is not well written, you can still understand it)

Make a chat room

Server side: socket.php

//创建websocket服务器对象,监听0.0.0.0:9502端口
$ws = new swoole_websocket_server("0.0.0.0", 9502);

//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
  $fd[] = $request->fd;
  $GLOBALS['fd'][] = $fd;
  //$ws->push($request->fd, "hello, welcome\n");
});

//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
  $msg = 'from'.$frame->fd.":{$frame->data}\n";
//var_dump($GLOBALS['fd']);
//exit;
  foreach($GLOBALS['fd'] as $aa){
    foreach($aa as $i){
      $ws->push($i,$msg);
    }
  }
  // $ws->push($frame->fd, "server: {$frame->data}");
  // $ws->push($frame->fd, "server: {$frame->data}");
});

//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
  echo "client-{$fd} is closed\n";
});

$ws->start();
Copy after login

Client: Socket.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div id="msg"></div>
<input type="text" id="text">
<input type="submit" value="发送数据" onclick="song()">
</body>
<script>
  var msg = document.getElementById("msg");
  var wsServer = 'ws://192.168.1.253:9502';
  //调用websocket对象建立连接:
  //参数:ws/wss(加密)://ip:port (字符串)
  var websocket = new WebSocket(wsServer);
  //onopen监听连接打开
  websocket.onopen = function (evt) {
    //websocket.readyState 属性:
    /*
    CONNECTING  0  The connection is not yet open.
    OPEN  1  The connection is open and ready to communicate.
    CLOSING  2  The connection is in the process of closing.
    CLOSED  3  The connection is closed or couldn't be opened.
    */
    msg.innerHTML = websocket.readyState;
  };

  function song(){
    var text = document.getElementById('text').value;
    document.getElementById('text').value = '';
    //向服务器发送数据
    websocket.send(text);
  }
   //监听连接关闭
//  websocket.onclose = function (evt) {
//    console.log("Disconnected");
//  };

  //onmessage 监听服务器数据推送
  websocket.onmessage = function (evt) {
    msg.innerHTML += evt.data +'<br>';
//    console.log('Retrieved data from server: ' + evt.data);
  };
//监听连接错误信息
//  websocket.onerror = function (evt, e) {
//    console.log('Error occured: ' + evt.data);
//  };

</script>
</html>
Copy after login

The above is the entire content of implementing PHP and websocket chat rooms based on Swoole. I believe this article will be helpful for everyone to learn PHP and websocket and develop chat rooms.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!