使用swoole编写超简单版IMI通信案例

使用swoole完成简单版的im通信案例,超简单版的通信。IMI通信是通过fd来通信的。真的美了,原来如此,但是这个是超简单版的通信案例,原生写的。怎么也没想到原来这么简单,说实话,码云,或者github真的很棒,自己略微有点基础,然后在借鉴一下别人写的代码,就会相对来说,很容易做出来东西,刚开始看别人写的代码真的很棒,码云和github真的很不错,由衷的赞美一下,多亏了别人的源代码了。别人估计也做不出来。

注意:

  1. 第一步,首先开启server类,php server.php
  2. websocket.html要通过窗口访问两边,这是因为,fd没做区分,如果不访问两边没法通信,做的很简陋,结合框架,redis完善一下。

php-server类

<?php
# 引入test测试类
include './test.php';

# 创建websokcet对象
$ws = new Swoole\WebSocket\Server('0.0.0.0',9502);

# 建立链接
$ws->on('Open',function($ws,$request){
  # 初始化通知信息
  $ws->push($request->fd,"您好?欢迎光临,我是客服某11某. \n ");
});

# 接受信息,并返回到webSoket中
$ws->on("Message",function($ws,$frame){
  # 将当前的fd.姑且当做进程ID,和发送的信息,已经当前的websocket对象传递到这个类中
  $resut = Test::demo($frame->fd,$frame->data,$ws);
  # 打印这个信息
  var_dump($resut);
});

# 关闭链接
$ws->on("Close",function($ws,$fd){
  echo "Client - {$fd} is closed \n";
});

# 启动服务
$ws->start();

 ?>

php - test类:用来处理一下数据信息,和对某个人发送信息

<?php

class Test
{
  public static function demo($fd, $message, $server)
  {
    # 因为原生的也是第一次做,就相对来说比较简陋,只能两个人通信,或许在使用框架完善。
    /*
    * 判断依据,如果当前的进程ID为1则是想要对2的人发送,如果不为1则表示当前的进程ID为2的对1发送信息
    */
      if($fd == 1)
      {
        $v_fd = 2;
      }else{
        $v_fd = 1;
      }

      # 格式化输出一下信息,
      $resut = self::reposon((int)$v_fd, 200, '来新信息了', $message, 'chatMessage');
      # 将格式化完的信息,通过websocket发送。
      $server->push($resut['fd'], $resut['data']);
      # 返回当前的数组信息,显示在控制台中
      return self::reposon($fd, 200, '信息发送成功', $message, 'message');
  }

  public static function reposon($fd, $code = 200, $msg = "操作成功", $data = '', $cmd = '')
    {
        $reposon['fd'] = $fd;
        $reposon['data'] = $data;

        return $reposon;
    }
}
 ?>

页面

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>WebSocket链接</title>
    <style media="screen">
    @charset "utf-8";
    body{
      font-family:verdana, Arial, Helvetica, "宋体", sans-serif;
      font-size: 12px;
    }

    body ,div ,dl ,dt ,dd ,ol ,li ,h1 ,h2 ,h3 ,h4 ,h5 ,h6 ,pre ,form ,fieldset ,input ,P ,blockquote ,th ,td ,img,
    INS {
      margin: 0px;
      padding: 0px;
      border:0;
    }
    ol{
      list-style-type: none;
    }
    img,input{
      border:none;
    }

    a{
      color:#198DD0;
      text-decoration:none;
    }
    a:hover{
      color:#ba2636;
      text-decoration:underline;
    }
    a{blr:expression(this.onFocus=this.blur())}/*去掉a标签的虚线框,避免出现奇怪的选中区域*/
    :focus{outline:0;}

    /*讨论留言添加表情*/
    .add_face{
      background-repeat: no-repeat;
      height: 24px;
      width: 24px;
      background-color: transparent;}
    /*视频聊天区*/
    .talk{
      height: 480px;
      width: 400px;
      margin:0 auto;
      border-left-width: 1px;
      border-left-style: solid;
      border-left-color: #444;
    }
    .talk_title{
      width: 100%;
      height:40px;
      line-height:40px;
      text-indent: 12px;
      font-size: 16px;
      font-weight: bold;
      color: #afafaf;
      background:#212121;
      border-bottom-width: 1px;
      border-bottom-style: solid;
      border-bottom-color: #434343;
      font-family: "微软雅黑";
    }
    .talk_title span{float:left}
    .talk_title_c {
      width: 100%;
      height:30px;
      line-height:30px;
    }
    .talk_record{
      width: 100%;
      height:398px;
      overflow: hidden;
      border-bottom-width: 1px;
      border-bottom-style: solid;
      border-bottom-color: #434343;
      margin: 0px;
    }
    .talk_word {
      line-height: 40px;
      height: 40px;
      width: 100%;
      background:#212121;
      text-align: center;
    }
    .messages {
      height: 24px;
      width: 240px;
      text-indent:5px;
      overflow: hidden;
      font-size: 12px;
      line-height: 24px;
      color: #666;
      background-color: #ccc;
      border-radius: 3px;
      -moz-border-radius: 3px;
      -webkit-border-radius: 3px;
    }
    .messages:hover{background-color: #fff;}
    .talk_send{
      width:50px;
      height:24px;
      line-height: 24px;
      font-size:12px;
      border:0px;
      margin-left: 2px;
      color: #fff;
      background-repeat: no-repeat;
      background-position: 0px 0px;
      background-color: dodgerblue;
      font-family: "微软雅黑";
    }
    .talk_send:hover {
      background-position: 0px -24px;
    }
    .talk_record ul{ padding-left:5px;}
    .talk_record li {
      line-height: 25px;
    }
    .talk_word .controlbtn a{
      margin: 12px;
    }
    .talk .talk_word .order {
      float:left;
      display: block;
      height: 14px;
      width: 16px;
      background-image: url(../images/loop.png);
      background-repeat: no-repeat;
      background-position: 0px 0px;
    }

    .talk .talk_word .loop {
      float:left;
      display: block;
      height: 14px;
      width: 16px;
      background-image: url(../images/loop.png);
      background-repeat: no-repeat;
      background-position: -30px 0px;
    }
    .talk .talk_word .single {
      float:left;
      display: block;
      height: 14px;
      width: 16px;
      background-image: url(../images/loop.png);
      background-repeat: no-repeat;
      background-position: -60px 0px;
    }
    .talk .talk_word .order:hover,.talk .talk_word .active{
      background-position: 0px -20px;
      text-decoration: none;
    }
    .talk .talk_word .loop:hover{
      background-position: -30px -20px;
      text-decoration: none;
    }
    .talk .talk_word .single:hover{
      background-position: -60px -20px;
      text-decoration: none;
    }

    /* * CSS Styles that are needed by jScrollPane for it to operate correctly. * * Include this stylesheet in your site or copy and paste the styles below into your stylesheet - jScrollPane * may not operate correctly without them. */
    .jspContainer{overflow:hidden;position:relative;}
    .jspPane{position:absolute;}
    .jspVerticalBar{position:absolute;top:0;right:0;width:8px;height:100%;background-color:transparent;}
    .jspHorizontalBar{position:absolute;bottom:0;left:0;width:100%;height:8px;background-color:transparent;}
    .jspVerticalBar *,.jspHorizontalBar *{margin:0;padding:0;}
    .jspCap{display:none;}
    .jspHorizontalBar .jspCap{float:left;}
    .jspTrack{
      position:relative;
      background-color:transparent;
    }
    .jspDrag{background:#ccc;position:relative;top:0;left:0;cursor:pointer;border:1px solid #333;-moz-border-radius:5px;-webkit-border-radius:5px;border-radius:5px;}
    .jspHorizontalBar .jspTrack,.jspHorizontalBar .jspDrag{float:left;height:100%;}
    .jspArrow{background:#50506d;text-indent:-20000px;display:block;cursor:pointer;}
    .jspArrow.jspDisabled{cursor:default;background:#80808d;}
    .jspVerticalBar .jspArrow{height:8px;}
    .jspHorizontalBar .jspArrow{width:8px;float:left;height:100%;}
    .jspVerticalBar .jspArrow:focus{outline:none;}
    .jspCorner{background:#eeeef4;float:left;height:100%;}
    /* Yuk! CSS Hack for IE6 3 pixel bug :( */
    * html .jspCorner{margin:0 -3px 0 0;}
    .jp-container{width:400px;height:400px;position:relative;background-color: #333;float:left;overflow: auto;}

    /*讨论区*/
    .jp-container .talk_recordbox{
      min-height:80px;
      color: #afafaf;
      padding-top: 5px;
      padding-right: 10px;
      padding-left: 10px;
      padding-bottom: 0px;
    }

    .jp-container .talk_recordbox:first-child{border-top:none;}
    .jp-container .talk_recordbox:last-child{border-bottom:none;}
    .jp-container .talk_recordbox .talk_recordtextbg{
      float:left;
      width:10px;
      height:30px;
      display:block;
      background-repeat: no-repeat;
      background-position: left top;}
    .jp-container .talk_recordbox .talk_recordtext{
      -moz-border-radius:5px;
      -webkit-border-radius:5px;
      border-radius:5px;
      background-color:#b8d45c;
      width:240px;
      height:auto;
      display:block;
      padding: 5px;
      float:left;
      color:#333333;
    }
    .jp-container .talk_recordbox h3{
      font-size:14px;
      padding:2px 0 5px 0;
      text-transform:uppercase;
      font-weight: 100;

    }
    .jp-container .talk_recordbox .user {
      float:left;
      display:inline;
      height: 45px;
      width: 45px;
      margin-top: 0px;
      margin-right: 5px;
      margin-bottom: 0px;
      margin-left: 0px;
      font-size: 12px;
      line-height: 20px;
      text-align: center;
    }
    /*自己发言样式*/
    .jp-container .talk_recordboxme{
      display:block;
      min-height:80px;
      color: #afafaf;
      padding-top: 10px;
      /* padding-right: 10px; */
      padding-left: 5px;
      padding-bottom: 0px;
    }
    .jp-container .talk_recordboxme .talk_recordtextbg{
      float:right;
      width:10px;
      height:30px;
      display:block;
      background-repeat: no-repeat;
      background-position: left top;}

    .jp-container .talk_recordboxme .talk_recordtext{
      -moz-border-radius:5px;
      -webkit-border-radius:5px;
      border-radius:5px;
      background-color:#fcfcfc;
      width:240px;
      height:auto;
      padding: 5px;
      color:#666;
      font-size:12px;
      float:right;

    }
    .jp-container .talk_recordboxme h3{
      font-size:14px;
      padding:2px 0 5px 0;
      text-transform:uppercase;
      font-weight: 100;
      color:#333333;

    }
    .jp-container .talk_recordboxme .user{
      float:right;
      height: 45px;
      width: 45px;
      margin-top: 0px;
      margin-right: 10px;
      margin-bottom: 0px;
      margin-left: 5px;
      font-size: 12px;
      line-height: 20px;
      text-align: center;
      display:inline;
    }
    .testDiv::-webkit-scrollbar { width: 12px;}/* 滚动槽 */
::-webkit-scrollbar-track { -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); border-radius: 10px;}/* 滚动条滑块 */
::-webkit-scrollbar-thumb { border-radius: 10px; background: rgba(0,0,0,0.1); -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.5);}::-webkit-scrollbar-thumb:window-inactive { background: rgba(255,0,0,0.4);}

    .talk_time{
      color: #666;
      text-align: right;
      width: 240px;
      display: block;
    }
    </style>
    <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"></script>
  </head>
  <body>
    <div class="talk">
    	<div class="talk_title"><span></span></div>
    	<div class="talk_record">
    		<div id="jp-container" class="jp-container">
    		</div>
    	</div>
    	<div class="talk_word">
    		&nbsp;
    		<input class="messages emotion" autocomplete="off" value=""/>
        <input class="talk_send" id='btn' type="button" title="" value="发送" />
    	</div>
    </div>
  </body>
</html>
<script type="text/javascript">
  var wsServer = 'ws://192.168.145.3:9502';
  var websocket = new WebSocket(wsServer);

  function gettime()
  {
    var date = new Date();
    return date.getFullYear() + "年"+ date.getMonth() + "月" + date.getDate() + "日 " + date.getHours() + '时' + date.getMinutes() + "分" + date.getSeconds()+"秒";
  }

  var nowtime = gettime();

  websocket.onopen = function (evt) {
      console.log("Connected to WebSocket server");
  };

  websocket.onclose = function (evt) {
      console.log("Disconnected");
  };

  websocket.onmessage = function (evt) {

      var admin = '	<div class="talk_recordbox"><div class="user"><span style="background-color:pink;width:50px;height:50px;display:block;border-radius:50%;"></span>机器人</div><div class="talk_recordtextbg">&nbsp;</div><div class="talk_recordtext"><h3>'+ evt.data +'</h3><span class="talk_time">'+ nowtime +'</span></div></div>'
      $(".jp-container").append(admin);
  };

  websocket.onerror = function (evt, e) {
      console.log('Error occured: ' + evt.data);
  };

  // 板顶点击事件,发送请求信息
  $("#btn").click(function(){
    var val = $(".emotion").val();

    if(val == "" || val == null || val == undefined)
    {
      alert("不能为空");
      return;
    }
    $(".emotion").val('');
    nowtime = gettime();
    var html = '<div class="talk_recordboxme"><div class="user"><span style="background-color:#ff0000;width:50px;height:50px;display:block;border-radius:50%;"></span>小明</div><div class="talk_recordtextbg">&nbsp;</div><div class="talk_recordtext"><h3>'+ val +'</h3><span class="talk_time">'+nowtime+'</span></div></div>';

    $(".jp-container").append(html);

    // 发送信息
    websocket.send(val);

    // 接受返回值
    websocket.onmessage = function (evt) {
        nowtime = gettime();
        var admin = '	<div class="talk_recordbox"><div class="user"><span style="background-color:pink;width:50px;height:50px;display:block;border-radius:50%;"></span>机器人</div><div class="talk_recordtextbg">&nbsp;</div><div class="talk_recordtext"><h3>'+ evt.data +'</h3><span class="talk_time">'+ nowtime +'</span></div></div>'
        $(".jp-container").append(admin);
    };
  })
</script>

例子:

使用swoole编写超简单版IMI通信案例
使用swoole编写超简单版IMI通信案例

上一篇:游戏笔记之《Fez》


下一篇:使用swoole实现tcp客户端