首先swoole是自己开发的web服务器 跟apache和nginx无关
1 首先开启端口 并且监听9502这个端 是否有客户端请求这个端口 ps:这里讲的是websocket 因为方便测试
//创建websocket服务器对象,监听0.0.0.0:9502端口
<pre><!--?php //创建websocket服务器对象,监听0.0.0.0:9502端口 端口号可以自定义哦 $ws = new swoole_websocket_server("0.0.0.0", 9502); //监听WebSocket连接打开事件 $ws->on('open', function ($ws, $request) {
var_dump($request->fd, $request->get, $request->server);
$ws->push($request->fd, "hello, welcome\n");
});
//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {
echo "Message: {$frame->data}\n";
$ws->push($frame->fd, "server: {$frame->data}");
});
//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
echo "client-{$fd} is closed\n";
});
$ws->start();
</pre>
<p>然后php 运行这个代码 就开启了端口<br ?-->
netstat -ntlp 查看端口 就有了
tcp 0 0 0.0.0.0:9502 0.0.0.0:* LISTEN 10328/php</pre>
第二部分 客户端websocket请求
<pre>
WebSocket Test
<script language="javascript" type="text/javascript">
var wsUri = "ws://ip:9502";
var output;
var ws = new WebSocket(wsUri);
//请求服务端后 成功后触发
ws.onopen = function () {
console.log('open');
ws.send('hello');
};
ws.onmessage = function (evt) {
console.log(evt.data)
};
//我关闭服务的时候 就会触发
ws.onclose = function (evt) {
console.log('WebSocketClosed!');
};
ws.onerror = function (evt) {
console.log('WebSocketError!');
};
</script>
</pre>
输出结果
<img class="alignnone size-medium wp-image-206" src="http://newmiracle.cn/wp-content/uploads/2016/10/QQ截图20161018105001-300x40.jpg" alt="qq%e6%88%aa%e5%9b%be20161018105001" width="300" height="40" />