天天看點

PHP基于swoole的websocket

常用指令:

  • 顯示啟用端口:sbin/iptables -L -n
  • 顯示程序:sudo ps -ef|grep php
  • 終止程序:sudo kill -9 pid 或者 sudo kill -15 pid
  • 開放端口的方法:
  1. 1. 開放端口指令: /sbin/iptables -I INPUT -p tcp --dport 8080 -j ACCEPT
               
  2. 2.儲存:/etc/rc.d/init.d/iptables save
               
  3. 3.重新開機服務:/etc/init.d/iptables restart
               
  4. 4.檢視端口是否開放:/sbin/iptables -L -n
               
  • swoole手冊
  • 服務端 websocket:
  • 注意:
  • 端口不能被占用
  • 建立websocket服務可參考swoole中快速入門代碼
<?php  
//建立websocket伺服器對象,監聽0.0.0.0:9509端口
$ws = new swoole_websocket_server("0.0.0.0", 9509);
//監聽WebSocket連接配接打開事件
$ws->on('open', function ($ws, $request) {
	$db = new MySQLi("47.104.70.24","csroot","usercseasy","guoyuan");
	$fd=$request->fd;
	$ipp = $request->get;
	$ip=$ipp['openid']; 
	$sql = "INSERT INTO testweb (fd,ip) VALUES ('{$fd}','{$ip}')";
    $reslut =$db->query($sql);
    var_dump($request->fd, $request->get, $request->server);
    $data=array($request->fd,'1');
    $ws->push($request->fd, 1);
});

//監聽WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
    echo "Message: {$frame->data}\n";
    // var_dump($ws->connections);
    //   $ws->push($frame->fd, 1);
     $grow=$frame->data;
     if ($grow<3) {
     	$grow++;
     }
     $ws->push($frame->fd, $grow);
    foreach ($ws->connections as $key => $value) {
    	if ($frame->fd !=$value) {
    		$ws->push($value, $grow);
    		
    	}
    }



});

//監聽WebSocket連接配接關閉事件
$ws->on('close', function ($ws, $fd) {
    echo "client-{$fd} is closed\n";
});
  

$ws->start();
?>
           
  • 浏覽器用戶端代碼
<!DOCTYPE html>
<html>
<head>

	<title></title>
</head>
<body>
    <img src="jd1.png" id="sss">
	<input type="text" name="shu" id="shu" value="">
	<button onclick="sendmsg()">澆水</button>
    <script src="jquery.js"></script>
<script type="text/javascript">
	
	var wsServer = 'ws://guoyuan.easy-all.cn:9509?openid=123';
var websocket = new WebSocket(wsServer);
//監聽連結
websocket.onopen = function (evt) {
    console.log(evt);
};
//監聽關閉
websocket.onclose = function (evt) {
    console.log("Disconnected");
};
//監聽服務發送消息
websocket.onmessage = function (evt) {
    if (evt.data==2) {
        $("#sss").attr('src',"jd2.png"); 
    }
     if (evt.data==3) {
        $("#sss").attr('src',"jd3.png"); 
    }
    console.log(evt);
};
//監聽異常
websocket.onerror = function (evt, e) {
    console.log('Error occured: ' + evt.data);
};
//js向伺服器發送消息
function sendmsg(){
            var content = $('#shu').val();
            
            $('#shu').val('')
            websocket.send(content);
        }
</script>
</body>
</html>
           
  • 小程式用戶端代碼
// pages/demo/demo.js
Page({

  /**
   * 頁面的初始資料
   */
  data: {
    status:'1',
    websoket:''

  },

  /**
   * 生命周期函數--監聽頁面加載
   */
  onLoad: function (options) {
    

  },
  water:function(e){
    console.log(1);
    var websoket=this.data.websoket; 
    websoket.send({
          data: this.data.status
        }) 
    
   
        },
  

  /**
   * 生命周期函數--監聽頁面初次渲染完成
   */
  onReady: function () {
    this.data.websoket = wx.connectSocket({
    //ws為http請求,wss為https
      url:
      'ws://47.104.70.24:9509?openid=12345',
    })

      // wx.onSocketMessage(function (e) {
      //   console.log(e)
      // })
    if (this.data.websoket) {
      this.data.websoket.onOpen(res => {
        console.log('監聽 WebSocket 連接配接打開事件。', res)
      })
      this.data.websoket.onClose(onClose => {
        console.log('監聽 WebSocket 連接配接關閉事件。', onClose)
      })
      this.data.websoket.onMessage(onMessage => {
        this.setData({
          status: onMessage.data
        })


        console.log('監聽WebSocket接受到伺服器的消息事件。伺服器傳回的消息', onMessage)
      }) 

      this.data.websoket.onError(onError => {
        console.log('監聽 WebSocket 錯誤。錯誤資訊', onError)
      })
      // this.data.websoket.onMessage(onMessage => {
      
      
      //   console.log('監聽WebSocket接受到伺服器的消息事件。伺服器傳回的消息', onMessage)
      // })
    }

  }