php swoole实现websocket长连接
创始人
2025-07-09 12:32:37
0

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

相关内容

热门资讯

修复:npm : 无法加载文件... 这个错误是由于 PowerShell 的执行策略限制导致的。在某些系统上,默认情况下,PowerSh...
弹性布局 布局的传统解决方案,基于盒状模型,依赖display属性+position属性+float属性。20...
html的data url和b... data urldata url的语法为:data:[][;base64],说明:(1)mediat...
fetch方式发送请求 1、以get方式发送查询字符串fetch("server.php?查询字符串"[,{method:"...
css实现内容裁剪 1、实现单行内容裁剪,后跟省略号overflow:hidden;text-overflow:elli...
css实现强制不换行/自动换行... 强制不换行white-space:nowrap;自动换行word-wrap: break-word;...
js设置html属性和CSS属... js设置html属性:(1)添加属性对象名.属性名=值对象名.setAttribute("属性名",...
php swoole实现web... 1、使用http连接websocket(ws://)服务器端:
ajax方式发送请求 1、以get方式发送查询字符串原生:var xhr=new XMLHttpRequest();xhr...
php中htmlentitie... htmlentities()和htmlspecialchars()这两个函数的功能都是转换字符为HT...