2010-06-26 241 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代码。