1.TCP搭建
<?php
$host = '192.168.50.66';
$port = 9501;
$serv = new swoole_server($host,$port);
$serv->on('connect',function($serv, $fd){
echo "建立连接
";
var_dump($serv, $fd);
});
$serv->on('receive',function($serv, $fd, $reactor_id, $data){
echo "收到消息
";
var_dump($data);
});
$serv->on('close',function($serv, $fd){
echo "关闭连接
";
var_dump($serv, $fd);
});
$serv->start();
2.UDP搭建
<?php
$serv = new swoole_server("192.168.50.66",11211,SWOOLE_PROCESS,SWOOLE_SOCK_UDP);
$serv->on('packet',function($serv,$data,$fd){
$serv->sendto($fd['address'],$fd['port'],"server:".$data);
var_dump($fd);
});
$serv->start();
3.web搭建
<?php
$serv = new swoole_http_server("192.168.50.66",9501);
$serv->on('request',function($request,$response){
$response->header("Content-Type","text/html;charset=utf-8");
$response->end("hello".rand(100,999));
});
$serv->start();
4.websocket搭建
<?php
$ws = new swoole_websocket_server('192.168.50.66',9501);
$ws->on('open',function($ws,$request){
var_dump($request);
$ws->push($request->fd,"welcome to hoewang");
});
$ws->on('message',function($ws,$request){
var_dump($request);
$ws->push($request->fd,"you send ".$request->data.'?');
});
$ws->on('close',function($ws,$request){
echo "close
";
});
$ws->start();
客户端代码JS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var wsServer = "ws://192.168.50.66:9501";
var webSocket = new WebSocket(wsServer);
webSocket.onopen = function(evt){
console.log('连接成功');
}
webSocket.onclose = function(evt){
console.log('断开连接');
}
webSocket.onmessage = function(evt){
console.log(evt.data);
}
webSocket.onerror = function(evt,e){
console.log('error');
}
webSocket->send('hehe');
</script>
</body>
</html>