websocket js php,php利用swoole和javascript实现websocket通信

1.安装swoole扩展,可自己编译或pecel install swoole

2.修改php.ini  增加 extension = “swoole.so”

3.命令行运行 php websocket.php

4.修改websocket.html的连接ip,浏览器运行http://127.0.0.1/swoole/websocket.html

websocket服务端代码  websocket.php

$server = new swoole_websocket_server(“0.0.0.0”, 9502);//0.0.0.0表示广播消息; 9502是刚才前端页面中定好的通信端口

$server->on(‘open’, function (swoole_websocket_server $server, $request) {

echo “server: handshake success with fd{$request->fd}n”;//$request->fd 是客户端id

});

$server->on(‘message’, function (swoole_websocket_server $server, $frame) {

echo “receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}n”;

//$frame->fd 是客户端id,$frame->data是客户端发送的数据

//服务端向客户端发送数据是用 $server->push( ‘客户端id’ ,  ‘内容’)

$data = $frame->data;

foreach($server->connections as $fd){

$server->push($fd , $data);//循环广播

}

});

$server->on(‘close’, function ($ser, $fd) {

echo “client {$fd} closedn”;

});

$server->start();

客户端js代码  websocket.html

Title

#danmu {

width: 40px;

height: 360px;

background-color: gray;

}

#send_box {

position: absolute;

top: 500px;

left: 100px;

}

console.log(‘尝试websocket和swoole的配合’);

var ws = new WebSocket(“ws://192.168.3.212:9502”);//一定要以ws://开头 ,端口是否可用(试验中可以直接关闭防火墙centos7用 systemctl stop firewalld.service ;7以下的用service iptables stop )

ws.onopen = function () {

console.log(“握手成功”);

ws.send(‘hello world!!!’);//向php服务器发送数据

};

ws.onmessage = function (e) {

console.log(“message:” + e.data);

var text_obj = ‘{ “text”:”‘ + e.data + ‘” , “color”:”red” ,”size”:”1″,”position”:”0″,”isnew”:” “}’;   //构造加上了innew属性的字符串danmu对象

console.log(text_obj);

var new_obj = eval(‘(‘ + text_obj + ‘)’);       //转化为js对象

document.getElementById(‘danmu’).innerHTML += text_obj+”n”;

//$(‘#danmu’).danmu(“add_danmu”, new_obj);   //向插件中添加该danmu对象

};

ws.onerror = function () {

console.log(“error”);

};

function send() {

console.log(document.getElementById(‘content’).value);

ws.send(document.getElementById(‘content’).value); //将input输入框中的文字发送给后端服务器,让后端服务器广播之

}

下载地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值