php swoole实现websocket长连接

1、使用http连接websocket(ws://)

服务器端:


<?php

$ws=new swoole_websocket_server("0.0.0.0",9501);

$ws->on("open",function($ws,$request){

  echo "新建连接:".$request->fd."\n";

});

$ws->on("close",function($ws,$fd){

  echo "关闭连接:".$fd."\n";

});

$ws->on("message",function($ws,$frame){

  echo "当前发送消息的连接:".$frame->fd."\n";

  foreach($ws->connections as $fd){  //$ws->connections为所有连接

    $ws->push($fd,$frame->data);  //$frame->data为服务器接收到的数据。

  }

});

$ws->start();

?>


客户端:


<script>

function onopen(){

  console.log("连接成功");

}

function onclose(){

  reconnect();

}

function onerror(){

  reconnect();

}

function onmessage(evt){

  document.getElementById("output")[xss_clean]=evt.data;  //evt.data为接收到的数据

}

function connect(){

  ws=new WebSocket("ws://10.110.21.22:9501");

  ws.onopen=onopen;

  ws.onclose=onclose;

  ws.onerror=onerror;

  ws.onmessage=onmessage;

}

var t=null;

function reconnect(){

  if(ws.readyState==1){  //0为正在连接,1为已连接,2为正在关闭,3为已关闭或连接失败

    clearTimeout(t);

  }else{

    if(ws.readyState==3){

      connect();

    }

    t=setTimeout("reconnect",100);

  }

}

connect();

function sendmessage(){

  var message="发送的内容";

  ws.send(message);  //发送数据

}

</script>


2、使用https连接websocket(wss://)

服务器端:


<?php 

$ws=new swoole_websocket_server("0.0.0.0",9501,SWOOLE_PROCESS,SWOOLE_TCP|SWOOLE_SSL);

$ws->set([

  'ssl_cert_file'=>'证书及其路径',

  'ssl_key_file'=>'密钥及其路径'

]);

$ws->on("open",function($ws,$request){  

});

$ws->on("close",function($ws,$fd){  

});

$ws->on("message",function($ws,$frame){

});

$ws-start();

?>


客户端:


<script>

function onopen(){

}

function onclose(){

  reconnect();

}

function onerror(){

  reconnect();

}

function onmessage(evt){  

}

function connect(){

  ws=new WebSocket("wss://10.110.21.31:9501");

  ws.onopen=onopen;

  ws.onclose=onclose;

  ws.onerror=onerror;

  ws.onmessage=onmessage;

}

var t=null;

function reconnect(){

  if(ws.readyState==1){

    clearTimeout(t);

  }else{

    if(ws.readyState==3){

      connect();

    }

    t=setTimeout("reconnect",100);

  }

}

connect();

function sendmessage(){

  ws.send("发送的数据");

}

</script>


注意:发起wss请求的页面必须使用https