码迷,mamicode.com
首页 > Web开发 > 详细

swoole webSocket服务

时间:2018-08-09 13:58:44      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:ima   ESS   local   soc   pre   get   nginx   src   trie   

socket.php

<?php
//创建websocket服务器对象,监听0.0.0.0:9502端口
$ws = new swoole_websocket_server("0.0.0.0", 9503);

//监听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();

socket.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>socket</title>

</head>
<body>
123
</body>
<script>
    var wsServer = ws://192.168.70.167:9503;
    var websocket = new WebSocket(wsServer);
    websocket.onopen = function (evt) {
        console.log("Connected to WebSocket server.");
    };

    websocket.onclose = function (evt) {
        console.log("Disconnected");
    };

    websocket.onmessage = function (evt) {
        console.log(Retrieved data from server:  + evt.data);
    };

    websocket.onerror = function (evt, e) {
        console.log(Error occured:  + evt.data);
    };
</script>
</html>

socket.php,socket.html  目录/usr/local/nginx/html/下

启动socket.php:

# php socket.php

启动socket.html

浏览器打开:192.168.70.167/socket.html

技术分享图片

swoole webSocket服务

标签:ima   ESS   local   soc   pre   get   nginx   src   trie   

原文地址:https://www.cnblogs.com/wesky/p/9448022.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!