zoukankan      html  css  js  c++  java
  • swoole的websockte例子

    服务器的环境,建议用bt.cn的一键环境

    服务端:

    <?php
    /**
     * Created by PhpStorm.
     * User: Administrator
     * Date: 2019523 0023
     * Time: 15:12
     */
    
    class Server{
    
        public function __construct()
        {
            $sw = new swoole_websocket_server('0.0.0.0',9501);
    
            $sw->on('open',function($server, $request){
    
                echo '客户端已经连接'.PHP_EOL;
            });
    
            $sw->on('message',function(swoole_websocket_server $server, $frame){
    
                echo PHP_EOL. '服务端已经收到消息';
                echo PHP_EOL. "客户端id: " .$frame->fd ; //客户端id
                echo PHP_EOL. "接收的消息: " .$frame->data ; //接收的数据
                $server->push($frame->fd,"服务把你的信息原封不动的给你了-->".$frame->data);
    
            });
    
            $sw->on('close',function($ser, $fd){
    
                echo '连接已经关闭';
            });
    
            $sw->start();
    
        }
    
    }
    
    new Server();

    客户端:

    <html>
    <head>
        <title>demo</title>
        <script src="https://cdn.bootcss.com/jquery/1.9.1/jquery.min.js"></script>
    </head>
    <body>
    <input type="text" id="content">
    <input type="button" value="send" id="send">
    <script type="text/javascript">
      var ws = new WebSocket("ws://192.168.56.101:9501");
      ws.onopen = function(){
        console.log("握手成功");
      }
      ws.onmessage = function(e){
        console.log("message:" + e.data);
      }
      ws.onerror = function(){
        console.log("error");
      }
      $("#send").click(function(){
        content = $("#content").val();
        console.log(content);
        ws.send(content);
      })
    </script>
    </body>
    </html>

    结果:

  • 相关阅读:
    编译原理-词法分析01-扫描程序
    编译原理-概论-02
    编译原理-概论-01
    web api :Action Results in Web API 2
    git 学习笔记7--branch
    git 学习笔记6--remote & log
    杭电acm 1230 火星a+b(进制)
    杭电acm 1214 圆桌会议(冒泡排序)
    杭电acm 1210 Eddy's 洗牌问题
    杭电acm 1207 汉诺塔II
  • 原文地址:https://www.cnblogs.com/fps2tao/p/10918620.html
Copyright © 2011-2022 走看看