16

我正在使用 javascript 连接 websocket:

<script>
    var socket;  
    var host = "ws://localhost:8000/socket/server/startDaemon.php";  
    var socket = new WebSocket(host);  
</script>

我得到了错误:

无法建立与服务器的连接

var host = "ws://localhost:8000/socket/server/startDaemon.php";
var socket = new WebSocket(host);

我该如何解决这个问题?

注意:我在 mozilla 中启用了 websocket 以支持 web socket 应用程序。当我在 chrome 中运行时出现错误:

   can't establish a connection to the server at ws://localhost:8000/socket/server/startDaemon.php. var socket = new WebSocket(host);
4

4 回答 4

5

显然,由于漏洞,firefox 4 禁用了 websockets。引用这篇文章:

Firefox 4 中禁用了 WebSocket

最近的发现发现,Websocket 使用的协议很容易受到攻击。Adam Barth 展示了一些针对该协议的严重攻击,攻击者可以使用这些攻击来毒化位于浏览器和 Internet 之间的缓存。

于 2011-06-02T05:45:50.663 回答
2

我通过此链接通过以下代码解决了我的错误

http://www.flynsarmy.com/2010/05/php-web-socket-chat-application/ 并为响应消息创建了 socketWebSocketTrigger.class.php 文件,其中代码为

class socketWebSocketTrigger
{   

        function responseMessage($param)
        {
            $a = 'Unknown parameter';

            if($param == 'age'){
                $a = "Oh dear, I'm 152";
            }

            if($param == 'hello'){
                $a = 'hello, how are you?';
            }

            if($param == 'name'){
                $a = 'my name is Mr. websocket';
            }

            if($param == 'today'){
                $a = date('Y-m-d');
            }

            if($param == 'hi'){
                $a = 'hi there';
            }

            return $a;

        }

}

并在“WebSocketServer.php”的发送函数中添加代码,用于调用响应请求消息的“responseMessage”函数

 public function send($client, $msg){
        $this->say("> ".$msg);
        $messageRequest = json_decode($msg,true);

            // $action=$messageRequest[0];
            $action = 'responseMessage';
            $param  = $messageRequest[1]['data'];
        if( method_exists('socketWebSocketTrigger',$action) ){
                                $response = socketWebSocketTrigger::$action($param);
                            }
            $msg = json_encode(
                array(                      
                'message',
                    array('data' => $response)
                )
            );

            $msg = $this->wrap($msg);

        socket_write($client, $msg, strlen($msg));
    }

它工作得很好。

于 2011-06-08T10:28:35.170 回答
1

您是否尝试在 Firefox 中运行客户端?根据文档

截至 2 月 10 日,唯一支持 websocket 的浏览器是 Google Chrome 和 Webkit Nightlies。从这里获取它 http://www.google.com/chrome

尝试在 Chrome 中运行它,看看它是否适合您。

于 2011-06-02T05:51:17.120 回答
1

首先,您的错误是使用带有 javascript 的 php 函数,require_once 'WebSocket.php';其次通过下面的链接中的教程。

http://net.tutsplus.com/tutorials/javascript-ajax/start-using-html5-websockets-today/

它工作正常。

谢谢,

于 2011-06-08T09:09:36.610 回答