php - swoole websocket无法console回调结果

查看:94
本文介绍了php - swoole websocket无法console回调结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

mac平台
我在学习websocket的过程中发现我无法console服务器中push回来的数据,甚至练onmessage函数也无法触发


-------------客户端代码-------:

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

</head>
<body>
<input  type="text" id="content">
<button  onclick="exampleSocket.send( document.getElementById('content').value )">发送</button>
<script type="text/javascript">

    var exampleSocket = new WebSocket("ws://127.0.0.1:9501");
    // Connection opened
    exampleSocket.onopen = function()

    {

        exampleSocket.send("我连接上了");

    };
    // Listen for messages
    exampleSocket.onmessage = function(evt)

    {
        var msg=JSON.parse(evt.data);
        console.log(msg+'1');

    };


</script>
</body>
</html>


------服务端的代码------:

<?php
$server = new swoole_websocket_server("127.0.0.1", 9501);

$server->on('open', function (swoole_websocket_server $server, $request) {
    echo "server: handshake success with fd{$request->fd}\n";
});

$server->on('message', function (swoole_websocket_server $server, $frame) {
    echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";



    $server->push($frame->fd, "this is server",1,true);
    #echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";

});

$server->on('close', function ($ser, $fd) {
    echo "client {$fd} closed\n";
});

$server->start();


客户端网页图片


但是发送信息后,在控制台并没有触发到console

解决方案

var msg=JSON.parse(evt.data);


不知道你怎么搞的呀!我试了试是可以的呀!

我在服务器上搞的,并不是在本地。客户端的ws地址是我服务器的外网IP,服务器端的地址是 0.0.0.0 并且 $server->push($frame->fd, $frame->data); 后面两个参数我没看不知道是神马意思着。。

你可以看一下我之前瞎搞的一个呀,一个基于Swoole的websocket聊天室

这篇关于php - swoole websocket无法console回调结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆