1. 聊天室模块发送数据交互处理;
- 创建 js 文件:
public/static/live/js/chart-push.js
$(function(){
$('#discuss-box').keydown(function(event){
if(event.keyCode == 13){
var text = $(this).val();
var url = 'http://192.168.2.214:8811?s=index/chart';
var data = {'content':text, 'game_id':1};
$.post(url, data, function (result) {
$(this).val("");
}, 'json');
}
});
});
2. 聊天室功能。
- 创建 js 文件:
public/static/live/js/chart.js
var wsUrl = "ws://192.168.2.214:8812";
var websocket = new WebSocket(wsUrl);
websocket.onopen = function(evt){
console.log("connected-swoole-success");
}
websocket.onmessage = function(evt){
console.log("ws-server-return-chart-data:" + evt.data);
pushChart(evt.data)
}
websocket.onclose = function(evt){
console.log("close");
}
websocket.onerror = function(evt, e){
console.log("error" + evt.data);
}
function pushChart(data){
data = JSON.parse(data);
html = '<div class="comment">';
html += '<span>'+data.user+'</span>';
html += '<span>'+data.content+'</span>';
html += '</div>';
$('#comments').prepend(html);
}
- 创建:
application/index/controller/Chart.php
<?php
namespace app\index\controller;
use app\common\lib\Util;
class Chart{
public function index(){
if(empty($_POST['game_id'])){
return Util::show(config('code.error'), 'error');
}
if(empty($_POST['content'])){
return Util::show(config('code.error'), 'error');
}
$data = [
'user' => '用户'. rand(0, 2000),
'content' => $_POST['content']
];
foreach($_POST['http_server']->ports[1]->connections as $fd) {
$_POST['http_server']->push($fd, json_encode($data));
}
return Util::show(config('code.success'), 'ok', $data);
}
}
<?php
class Ws {
CONST HOST = "0.0.0.0";
CONST PORT = 8811;
CONST CHART_PORT = 8812;
public $ws = null;
public function __construct() {
$this->ws = new swoole_websocket_server(self::HOST, self::PORT);
$this->ws->listen(self::HOST, self::CHART_PORT, SWOOLE_SOCK_TCP);
$this->ws->set([
'worker_num' => 4,
'task_worker_num' => 4,
'enable_static_handler' => true,
'document_root' => "/data/project/test/swoole/tp5/public/static",
]);
$this->ws->on("open", [$this, 'onOpen']);
$this->ws->on("message", [$this, 'onMessage']);
$this->ws->on("workerStart", [$this, 'onWorkerStart']);
$this->ws->on("request", [$this, 'onRequest']);
$this->ws->on("task", [$this, 'onTask']);
$this->ws->on("finish", [$this, 'onFinish']);
$this->ws->on("close", [$this, 'onClose']);
$this->ws->start();
}
public function onWorkerStart($server, $worker_id) {
define('APP_PATH', __DIR__ . '/../application/');
require __DIR__ . '/../thinkphp/start.php';
}
public function onRequest($request, $response) {
$_SERVER = [];
if(isset($request->server)) {
foreach($request->server as $k => $v) {
$_SERVER[strtoupper($k)] = $v;
}
}
if(isset($request->header)) {
foreach($request->header as $k => $v) {
$_SERVER[strtoupper($k)] = $v;
}
}
$_FILES = [];
if(isset($request->files)) {
foreach($request->files as $k => $v) {
$_FILES[$k] = $v;
}
}
$_GET = [];
if(isset($request->get)) {
foreach($request->get as $k => $v) {
$_GET[$k] = $v;
}
}
$_POST = [];
if(isset($request->post)) {
foreach($request->post as $k => $v) {
$_POST[$k] = $v;
}
}
$_POST['http_server'] = $this->ws;
ob_start();
try{
think\Container::get('app', [APP_PATH])->run()->send();
}catch(\Exception $e){
}
$res = ob_get_contents();
ob_end_clean();
$response->end($res);
}
public function onTask($serv, $task_id, $workerId, $data){
$obj = new app\common\lib\task\Task;
$method = $data['method'];
$flag = $obj->$method($data['data'], $serv);
return $flag;
}
public function onFinish($serv, $taskId, $data){
echo "taskId:{$taskId}\n";
echo "finish-data-success:{$data}\n";
}
public function onOpen($ws, $request){
$info = $ws->connection_info($request->fd);
if($info['server_port'] == self::PORT){
\app\common\lib\redis\Predis::getInstance()->sAdd(config('redis.live_game_key'), $request->fd);
}
echo "open - {$request->fd} \n";
}
public function onMessage($ws, $frame){
echo "server-push-message:{$frame->data}\n";
}
public function onClose($ws, $fd){
\app\common\lib\redis\Predis::getInstance()->sRem(config('redis.live_game_key'), $fd);
echo "closed - clientId: {$fd} \n";
}
}
new Ws();