WebSocket:无法在客户端接收消息

问题描述:

我正在使用Rachet并尝试给出的代码为here。在我的Chrome控制台窗口中运行以下代码后,我看不到任何消息。 conn.send()说未定义:WebSocket:无法在客户端接收消息

var conn = new WebSocket('ws://localhost:8080'); 
conn.onopen = function(e) { 
    console.log("Connection established!"); 
}; 

conn.onmessage = function(e) { 
    console.log(e.data); 
}; 

更新

代码在服务器端:在行动

public function onMessage(ConnectionInterface $from, $msg) { 
     $numRecv = count($this->clients) - 1; 
     echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n" 
      , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's'); 

     foreach ($this->clients as $client) { 
      if ($from !== $client) { 
       print "Someone else is here"; 
       // The sender is not the receiver, send to each client connected 
       $msg = ' Server responds:- '.$msg; 
       $client->send($msg); 
      } 
     } 
    } 

见客户端和服务器 enter image description here

更新#2

似乎以下检查问题:

if ($from !== $client) {} 

但在去除,这是广播到所有的客户端连接,而到谁发送的消息

+0

你能分享你的php代码吗?特别是您存储/保存连接的客户端的位置? – brense

+0

@brense它在这里'聊天类'http://socketo.me/docs/hello-world – Volatil3

+0

好吧,在聊天服务器窗口中,你看到你的客户端连接? '新的连接! xxx' – brense

原来,这个问题是这条线在服务器上的一个结束:

if ($from !== $client) {} 

这不是让服务器对各自的客户响应,并打算回应,如果它是该客户端。我只是将其更改为:

if ($from === $client) {} 

它对我很有用。在示例代码中给出的!==是一个典型的聊天应用程序,其中一个客户会跟其他的,而在我的情况下,它只会是一个Server <->Client

+0

您也可以将if语句全部删除,以便将邮件发送给所有客户端,无论他们是否为发件人 – brense

@ Volatil3,你也许可以尝试一下我的包https://github.com/php-pure/sacky-serverhttps://github.com/php-pure/sacky-client

我有一个类的解释,处理channel基地,同时与socket.io

在sacky服务器,执行控制台/tests/run,然后在sacky客户端,位于channel/channel.html开2浏览器标签。