123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- <?php
- use Workerman\Worker;
- use Workerman\Protocols\Http\Request;
- include __DIR__ . '/vendor/autoload.php';
- // 启动tcp端口
- $tcp_worker = new Worker('tcp://127.0.0.1:2220');
- $tcp_worker->onWorkerStart = function()
- {
- // 启动http端口(用来主动推送)
- $http_worker = new Worker('http://127.0.0.1:2221');
- $http_worker->onMessage = function ($connection, Request $request){
- $post = $request->post();
- $post = $post ? $post : $request->get();
- $msg_data = isset($post['data']) ? $post['data'] : false;
- global $tcp_worker;
- if($msg_data && count($tcp_worker->connections) > 0){
- // 获取tcp Worker 实例
- foreach($tcp_worker->connections as $tcp_connection)
- {
- $tcp_connection->send($msg_data);
- }
- return $connection->send('发送成功!内容:' . $msg_data);
- }
- return $connection->send('发送失败!');
- };
- // 监听http
- $http_worker->listen();
- };
- // 当接收到tcp客户端请求时
- $tcp_worker->onMessage = function ($connection, $data){
- $msg = doEncoding($data);
- $msg_data = date('Y-m-d H:i:s') . '接收消息:' . $msg . PHP_EOL . PHP_EOL;
- file_put_contents('./data.txt', $msg_data, FILE_APPEND);
- $connection->send(date('Y-m-d H:i:s').'----收到消息:' . $msg);
- };
- /**
- * 将socket接收到的乱码字符转为UTF-8字符
- * @param string $str
- * @return string
- */
- function doEncoding($str)
- {
- $encode = strtoupper(mb_detect_encoding($str, ["ASCII", 'UTF-8', "GB2312", "GBK", 'BIG5']));
- if ($encode != 'UTF-8') {
- $str = mb_convert_encoding($str, 'UTF-8', $encode);
- }
- return $str;
- }
- // 运行worker
- Worker::runAll();
|