安装Swoole
过程中使用pecl install swoole进行安装swoole,所以要求php版本大于7.0.0
如果已经安装了5.4或者其他版本可以进行卸载低版本
rpm -qa |grep php|xargs rpm -e
更新yum源
rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-7.rpm
查看php7.x可用版本
yum serach php7
安装
yum -y install php72w php72w-cli php72w-common php72w-devel php72w-embedded php72w-fpm php72w-gd php72w-mbstring php72w-mysqlnd php72w-opcache php72w-pdo php72w-xml
查看7.x版本是否已安装
php -v
安装pecl
yum install php72w-pear
用pecl安装swoole
pecl install swoole
在php.ini添加extension=swoole.so
执行
php -m
如果有swoole就成功了
官网demo socket.php
<?php
$server = new swoole_websocket_server("192.168.5.87", 9501);
$server->on('open', function (swoole_websocket_server $server, $request) {
file_put_contents( __DIR__ .'/log.txt' , $request->fd);
});
$server->on('message', function (swoole_websocket_server $server, $frame) {
global $client;
$data = $frame->data;
$m = file_get_contents( __DIR__ .'/log.txt');
for ($i=1 ; $i<= $m ; $i++) {
echo PHP_EOL . ' i is ' . $i . ' data is '.$data . ' m = ' . $m;
$server->push($i, $data );
}
});
$server->on('close', function ($ser, $fd) {
echo "client {$fd} closed\n";
});
$server->start();
html代码 socket.html
<!DOCTYPE html>
<html>
<head>
<title>聊天室</title>
<meta charset="UTF-8">
<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script>
<script type="text/javascript">
var exampleSocket = new WebSocket("ws://192.168.5.87:9501");
exampleSocket.onopen = function (event) {
exampleSocket.send(returnCitySN["cip"]+','+returnCitySN["cname"]);
};
exampleSocket.onmessage = function (event) {
var element = document.getElementById("item");
element.innerHTML += '<p>'+event.data+'</p>';
document.getElementById("content").value = ' ';
}
document.onkeydown = function(e){
if(e.keyCode == 13){
exampleSocket.send(document.getElementById('content').value);
}
}
</script>
</head>
<body>
<div id="item"></div>
<input type="text" id="content">
<button onclick="exampleSocket.send(document.getElementById('content').value)">发送</button>
</body>
</html>
网友评论