2016-04-05 72 views
1

我正在使用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

回答

0

原來,這個問題是這條線在服務器上的一個結束:

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

這不是讓服務器對各自的客戶響應,並打算迴應,如果它是該客戶端。我只是將其更改爲:

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

它對我很有用。在示例代碼中給出的!==是一個典型的聊天應用程序,其中一個客戶會跟其他的,而在我的情況下,它只會是一個Server <->Client

+0

您也可以將if語句全部刪除,以便將郵件發送給所有客戶端,無論他們是否爲發件人 – brense