websocket协议是基于TCP的一种新网络协议,它实现了浏览器与服务器全双工(full-duplex)通信--可以让服务器主动发送信息给客户端

为什么用websocket

HTTP的通信只能由客户端发起,比如ajax轮寻啊

websocket特点:

1.建立在TCP协议之上

2.性能开销小通信高效

3.客户端可以与任意服务器通信

4.协议标识符WS WSS跟HTTPS一个概念

5.持久化网络通信协议 服务器主动向客户端推送消息

<?php

$server = new swoole_websocket_server("0.0.0.0", 9504);

//设置WebSocket子协议。设置后握手响应的Http头会增加Sec-WebSocket-Protocol: {$websocket_subprotocol}
//$server->set([
//    'websocket_subprotocol' => 'chat',
//]);

//----------------
//监听websocke连接打开事件
//$server->on('open', function (swoole_websocket_server $server, $request) {
//    echo "server: handshake success with fd{$request->fd}\n";
//});
//也可以用以下的写法
$server->on('open', 'onOpen');
function onOpen($server, $request){
    //哪个客户端
    print_r($request->fd);

}
//---------------

//监听消息事件
$server->on('message', function (swoole_websocket_server $server, $frame) {
    echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
    //向websocket客户端连接推送数据
    //    $fd 客户端连接的ID,如果指定的$fd对应的TCP连接并非websocket客户端,将会发送失败
    //$data 要发送的数据内容
    //$opcode,指定发送数据内容的格式,默认为文本。发送二进制内容$opcode参数需要设置为WEBSOCKET_OPCODE_BINARY
    //发送成功返回true,发送失败返回false
    //    function swoole_websocket_server->push(int $fd, string $data, int $opcode = 1, bool $finish = true);
    $server->push($frame->fd, "this is server");
});
//也可以用以上单独方法去写

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

//$server->on('request', function (swoole_http_request $request, swoole_http_response $response) {
//    global $server;//调用外部的server
//    // $server->connections 遍历所有websocket连接用户的fd,给所有用户推送
//    foreach ($server->connections as $fd) {
//        $server->push($fd, $request->get['message']);
//    }
//});
$server->start();

//class WebsocketTest {
//    public $server;
//    public function __construct() {
//        $this->server = new swoole_websocket_server("0.0.0.0", 9501);
//        $this->server->on('open', function (swoole_websocket_server $server, $request) {
//            echo "server: handshake success with fd{$request->fd}\n";
//        });
//        $this->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, "this is server");
//        });
//        $this->server->on('close', function ($ser, $fd) {
//            echo "client {$fd} closed\n";
//        });
//        $this->server->on('request', function ($request, $response) {
//            // 接收http请求从get获取message参数的值,给用户推送
//            // $this->server->connections 遍历所有websocket连接用户的fd,给所有用户推送
//            foreach ($this->server->connections as $fd) {
//                $this->server->push($fd, $request->get['message']);
//            }
//        });
//        $this->server->start();
//    }
//}
//new WebsocketTest();
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>ws test</h1>
<script>
    var wsUrl = 'ws://10.200.9.221:9504';
    var webSocket = new WebSocket(wsUrl);
    //实例对象的onopen的属性
    webSocket.onopen = function (p1) {//发服务器发数据
        webSocket.send('hello ws');
        console.log('con-swoole-succ');
    };

    //实例化 onmessage
    webSocket.onmessage = function (p1) {console.log('ws-server-return-data:'+ p1.data);
    };

    //onclose
    webSocket.onclose = function (p1) {console.log('close');
    };

    webSocket.onerror = function (p1) {console.log('error-data:'+ p1.data);
    }
</script>
</body>
</html>

浏览器如果报以下错误

ws.html:11 WebSocket connection to 'ws://10.200.9.221:9504/' failed: Error i

请查看一下你的防火墙,是否开放此端口

<?php

class wsServer
{
    const Host = '0.0.0.0';
    const PORT = '9504';
    public $ws = null;

    function __construct()
    {
        $this->ws = new swoole_websocket_server(self::Host, self::PORT);
        $this->ws->on('open', [$this, 'onOpen']);
        $this->ws->on('message', [$this, 'onMessage']);
        $this->ws->on('close', [$this, 'onClose']);
        $this->ws->start();
    }

    /**
     * 监听websocke连接打开事件
     * @param $server
     * @param $request
     */
    function onOpen($server, $request)
    {
        print_r($request->fd);

    }

    /**
     * 监听消息事件
     * websocket客户端连接推送数据
     * $fd 客户端连接的ID,如果指定的$fd对应的TCP连接并非websocket客户端,将会发送失败
     * $data 要发送的数据内容
     * $opcode,指定发送数据内容的格式,默认为文本。发送二进制内容$opcode参数需要设置为WEBSOCKET_OPCODE_BINARY
     * 发送成功返回true,发送失败返回false
     * function swoole_websocket_server->push(int $fd, string $data, int $opcode = 1, bool $finish = true);
     * @param $ws
     * @param $frame
     */
    function onMessage($ws, $frame)
    {
        echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
        $ws->push($frame->fd, "this is server");
    }

    /**
     * 关闭
     * @param $ws
     * @param $fd
     */
    function onClose($ws, $fd)
    {
        echo "client {$fd} closed\n";
    }
}

$ws = new wsServer();

swoole websocket服务相关推荐

  1. Swoole WebSocket服务使用Task任务详解 (面向对象方法)

    Swoole WebSocket服务使用Task任务详解 (面向对象方法) 作者: 绝爱七八丶 博客: https://blog.csdn.net/qq_40193451 日期: 2018.8.24 ...

  2. PHP 接收 UDP包_php只能做网站?基于swoole+websocket开发双向通信应用

    前言 众所周知,PHP用于开发基于HTTP协议的网站应用非常便捷.而HTTP协议是一种单向的通信协议,只能接收客户端的请求,然后响应请求,不能主动向客户端推送信息.因此,一些实时性要求比较高的应用,如 ...

  3. php websocket udp,swoole创建websocket服务并且支持https服务,同时监听tcp,udp端口

    namespace serve\websocket; // use serve\websocket\task\Message as taskMessage; use serve\websocket\c ...

  4. thinkphp6+swoole websocket使用教程自研路线不建议使用

    转载请注明: 藏羚骸的博客~thinkphp6+swoole websocket使用教程自研路线不建议使用. 介绍 对于think-swoole网上资料五花八门,根据网上资料,我成功走上了岔路口,但是 ...

  5. css3 wshtml_swoft框架之websocket服务的简单使用

    本篇博文相关环境版本如下: OS系统:CentOS Linux release 7.7 php版本:PHP 7.2.24 swoole版本:4.4.14 swoft版本:2.0.7 swoft框架的介 ...

  6. php 游戏开发swoole,Swoole+websocket多人在线游戏示例

    利用Swoole,可以使用PHP来开发Websocket服务器,实现多人在线游戏.本文通过一个最简单的摇骰子游戏来介绍Server端(由PHP+Swoole实现)和Client端(由H5+Websoc ...

  7. 使用websocket-sharp来创建c#版本的websocket服务

    当前有一个需求,需要网页端调用扫描仪,javascript不具备调用能力,因此需要在机器上提供一个ws服务给前端网页调用扫描仪.而扫描仪有一个c#版本的API,因此需要寻找一个c#的websocket ...

  8. 在Apache上搭建pywebsocket提供html5的websocket服务

    参考:http://www.travisglines.com/web-coding/how-to-set-up-apache-to-serve-html5-websocket-applications ...

  9. 三分钟构建高性能 WebSocket 服务 | 超优雅的 SpringBoot 整合 Netty 方案

    前言 每当使用SpringBoot进行Weboscket开发时,最容易想到的就是spring-boot-starter-websocket(或spring-websocket).它可以让我们使用注解, ...

最新文章

  1. 使用条件编译加密报文
  2. 20、Power Query-数据合并、拆分
  3. 深入探讨C++中的引用(转)
  4. 国家电网是“围城”?辞职吗?
  5. [蓝桥杯][算法提高]能量项链(区间dp)
  6. Hades:移动端静态分析框架
  7. vue实现两重列表集合,点击显示,点击隐藏的折叠效果,(默认显示集合最新一条数据,点击展开,显示集合所有数据)...
  8. html是非结构数据吗,Python处理非结构数据
  9. 基于channel的goroutine
  10. 3-12岁经典必读书
  11. win10自动更新系统导致 点击睡眠之后直接关机
  12. ubuntu下vscode字体高与缩进不成比
  13. 可以免费测试的短信验证码接口接入
  14. Spring学习传送门
  15. 关于法线贴图、颜色贴图和高光贴图
  16. [转贴]IE中 无法打开internet站点 。。。。。
  17. CentOS 6.8 Local time zone must be set--see zic manual page
  18. linux 繁体中文转为简体,linux - 安装OpenCC(简体繁体转换)
  19. Java Jsp+mysql实现企业财务管理系统(普通职工/管理员 员工、公司资产、经营、费用管理)
  20. FPGA存储块,有没有使能Primitives output Register作用

热门文章

  1. 线程编程常见API简介(上)
  2. 恶意软件、Rootkit和僵尸网络
  3. BGP community
  4. [导入]关于DataGrid等控件中的自动编号
  5. OpenCV 车道线提取
  6. 数据库管理工具 FileMaker Pro 17 Advanced v17.0.4.400中文版
  7. 【多线程】学习记录七种主线程等待子线程结束之后在执行的方法
  8. laravel的redis配置,一直报错Class 'Predis\Client' not found
  9. 如何理解 Web API
  10. postgresql安装指南