第一步:下载tp3.2.3、GatewayWorker、GatewayClient;
解压后把tp和Gatewayworker放在同一个目录下面(根目录下面);
第二步:将GatewayClient中的Gateway.php重命名为Gateway.class.php;
修改其内容如下:
1.namespace Org\Util;
2.第35行的$registerAddress的端口号修改和GatewayWorker/Application/YourApp/下的三个start_文件里面的“服务注册地址”下端口号一致;
保存后将该文件放于tp框架的ThinkPHP/Library/Org/Util文件夹下;
第三步:将GatewayWorker中start_gateway.php的第24行Gateway括号内容修改为(“websocket://后面的不变”);
Events.php的第40行修改为Gateway::sendToClient($client_id,json_encode(array('client_id'=>$client_id)));可注释第42行代码;
第四步:运行tp入口文件后,控制器Index.class.php文件内容如下:
<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
// public $uid = 2;
public function index() {
// $this->uid = I('uid');
session('uid', $this->uid);
$this->display();
}
function bind() {
$uid = session('uid');
$client_id = I('client_id');
$gateway = new \Org\Util\Gateway();
$gateway->bindUid($client_id, $uid);
$message = '绑定成功' . $uid . '-' . $client_id;
$gateway->sendToUid($uid, $message);
}
function message() {
$to_uid = I('uid');
$message = I('msg');
$gateway = new \Org\Util\Gateway();
$data['msg'] = $message;
$data['from_uid'] = session('uid');
$data['to_uid'] = $to_uid;
$gateway->sendToUid($to_uid, json_encode($data));
//发给对方
$gateway->sendToUid($data['from_uid'], json_encode($data));
//发给自己
echo json_encode($data);
}
}
视图文件index.html文件内容为:(其他文件自己建,不贴了)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>chatroom</title>
<script type="text/javascript" src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
// 打开一个 web socket
var ws = new WebSocket("ws://127.0.0.1:8282");
ws.onopen = function() {};
ws.onmessage = function(evt) {
var received_msg = evt.data;
console.log(received_msg);
// alert("数据已接收..." + received_msg);
var jmsg = JSON.parse(received_msg);
if (jmsg.from_uid > 0) {
var t_msg = '<li>' + jmsg.from_uid + ' 说:' + jmsg.msg + '</li>';
$("#message").append(t_msg);
}
if (jmsg.client_id.length != 0) {
$.post("{:U('Index/bind')}", {
client_id: jmsg.client_id
},
function(data) {
console.log(data);
});
}
}
</script>
</head>
<body>
<ul id="message">
</ul>
<div>
<input name="uid" value="1" />
<input name="msg" value="" size="50" />
<button type="button" id="send">发送</button>
</div>
<script>
$(function() {
$("#send").click(function() {
var uid = $('input[name="uid"]').val();
var msg = $('input[name="msg"]').val();
$.post("{:U('Index/message')}", {
uid: uid,
msg: msg
},
function(data) {
$('input[name="msg"]').val('');
});
});
});
</script>
</body>
</html>