2010-06-26 237 views
0

我正在嘗試使用HTML5/JS API創建一個簡單的WebSocket示例。根據我在服務器上追蹤的內容,看起來套接字正在連接,但沒有任何事件觸發(onopen,onmessage,onclose等)。我是Flash開發人員,所以我不擅長調試JavaScript,我希望有人能幫助我。這是我正在使用的客戶端代碼。WebSocket不會觸發事件

<script type="text/javascript" charset="utf-8"> 
    function startSocket() 
    { 
     if("WebSocket" in window) 
     { 
      var ws = new WebSocket("ws://localhost:1740"); 

      ws.onopen = function() { 
       window.alert("open!"); 
      } 

      ws.onmessage = function(event) { 
       window.alert(event.data); 
      } 

      ws.onclose = function() { 
       window.alert("Closed"); 
      } 

      ws.onerror = function() { 
       window.alert("trouble in paradise"); 
      }   
     } 

    } 


</script> 

這裏是我的套接字服務器代碼(它可以在Flash中正常工作,但這可能並不意味着什麼)。

<?php 

create_connection('localhost',1740); 

function create_connection($host,$port) 
{ 
    $socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP); 

    if (!is_resource($socket)) { 
     echo 'Unable to create socket: '. socket_strerror(socket_last_error()) . PHP_EOL; 
    } else { 
     echo "Socket created.\n"; 
    } 

    if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) { 
     echo 'Unable to set option on socket: '. socket_strerror(socket_last_error()) . PHP_EOL; 
    } else { 
     echo "Set options on socket.\n"; 
    } 

    if (!socket_bind($socket, $host, $port)) { 
     echo 'Unable to bind socket: '. socket_strerror(socket_last_error()) . PHP_EOL; 
    } else { 
     echo "Socket bound to port $port.\n"; 
    } 

    if (!socket_listen($socket,SOMAXCONN)) { 
     echo 'Unable to listen on socket: ' . socket_strerror(socket_last_error()); 
    } else { 
     echo "Listening on the socket.\n"; 
    } 

    while (true) 
    { 
     $connection = @socket_accept($socket); 

     if($connection) 
     {  
      echo "Client $connection connected!\n"; 
      send_data($connection); 

     } else { 
      echo "Bad connection."; 
     } 
    } 
} 

function send_data($connection) 
{ 
    echo $connection; 
    // Create a number between 30 and 32 that will be our initial stock price. 
    $stock_price = rand(30,32); 
    while (true) 
    { 
     socket_write($connection,"$stock_price\n",strlen("$stock_price\n")); 
     sleep(1); 

     // Generate a random number that will represent how much our stock price 
     // will change and then make that number a decimal and attach it to the 
     // previous price. 
     $stock_offset = rand(-50,50); 
     $stock_price = $stock_price + ($stock_offset/100); 
     echo "$stock_price\n"; 
    } 
} 


?> 

在此先感謝。

=瑞恩

回答

0

也許這是完全明顯的,但如果其他人得到這個問題,你需要添加一個握手。在Flash中,這不是必需的,我仍然不完全理解它,但是我能夠修改此項目 - http://code.google.com/p/phpwebsocket/ - 它的工作原理是在我的socket_accept代碼運行後添加gethandshake代碼。