swoole安装基本配置

php安装swoole

1. 下载swoole安装

```
wget http://pecl.php.net/get/swoole-1.9.1.tgz
tar -zxvf swoole-1.9.1.tgz
cd swoole-1.9.1
phpize
./configure
make
make install
```
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

2. 在php.ini添加swoole.so

```
extension=swoole.so
```
  • 1
  • 2
  • 3
  • 4

3. php文件

```
<?php
$server = new swoole_websocket_server("0.0.0.0", 9501);

$server->on('open', function (swoole_websocket_server $server, $request) {
    echo "server: handshake success with fd{$request->fd}\n";
});

$server->on('message', function (swoole_websocket_server $server, $frame) {
    echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
    $server->push($frame->fd, "这是服务器消息!");
});

$server->on('close', function ($ser, $fd) {
    echo "client {$fd} closed\n";
});

$server->start();
```
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

4. html文件

```
<!DOCTYPE html>
<html>
<head>
    <title>欢迎使用swoole!</title>
</head>
<body>
<script type="text/javascript">
    // 创建一个Socket实例
    var socket = new WebSocket('ws://192.168.1.127:9501/');

    // 打开Socket
    socket.onopen = function(event) {

      // 发送一个初始化消息
      socket.send('我是客户端并且正在监听。');

      // 监听消息
      socket.onmessage = function(event) {
        console.log('客户端接收到一个消息。',event);
      };

      // 监听Socket的关闭
      socket.onclose = function(event) {
        console.log('客户端通知套接字已关闭。',event);
      };

      // 关闭Socket....
      //socket.close()
    };
</script>
<h1>欢迎使用swoole!</h1>
</body>
</html>
```
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

5. 打开防火墙9501端口

```
firewall-cmd --zone=public --add-port=9501/tcp --permanent
systemctl restart firewalld
```
  • 1
  • 2
  • 3
  • 4
  • 5

6.. 启动swoole服务

```
php /usr/local/nginx-1.11.5/html/index.php
```

来源:https://blog.csdn.net/aojianmo2012/article/details/55046571

猜你喜欢

转载自blog.csdn.net/gb4215287/article/details/81081570