如何在PHP中创建websockets服务器

是否有任何教程或指南显示如何在PHP中编写一个简单的websockets服务器?我试过在谷歌上寻找它,但我找不到很多。我发现phpwebsockets但它现在已经过时,不支持最新的协议。我自己尝试更新它,但似乎没有用。


#!/php -q

<?php  /*  >php -q server.php  */


error_reporting(E_ALL);

set_time_limit(0);

ob_implicit_flush();


$master  = WebSocket("localhost",12345);

$sockets = array($master);

$users   = array();

$debug   = false;


while(true){

  $changed = $sockets;

  socket_select($changed,$write=NULL,$except=NULL,NULL);

  foreach($changed as $socket){

    if($socket==$master){

      $client=socket_accept($master);

      if($client<0){ console("socket_accept() failed"); continue; }

      else{ connect($client); }

    }

    else{

      $bytes = @socket_recv($socket,$buffer,2048,0);

      if($bytes==0){ disconnect($socket); }

      else{

        $user = getuserbysocket($socket);

        if(!$user->handshake){ dohandshake($user,$buffer); }

        else{ process($user,$buffer); }

      }

    }

  }

}


//---------------------------------------------------------------

function process($user,$msg){

  $action = unwrap($msg);

  say("< ".$action);

  switch($action){

    case "hello" : send($user->socket,"hello human");                       break;

    case "hi"    : send($user->socket,"zup human");                         break;

    case "name"  : send($user->socket,"my name is Multivac, silly I know"); break;

    case "age"   : send($user->socket,"I am older than time itself");       break;

    case "date"  : send($user->socket,"today is ".date("Y.m.d"));           break;

    case "time"  : send($user->socket,"server time is ".date("H:i:s"));     break;

    case "thanks": send($user->socket,"you're welcome");                    break;

    case "bye"   : send($user->socket,"bye");                               break;

    default      : send($user->socket,$action." not understood");           break;

  }

}


function send($client,$msg){

  say("> ".$msg);

  $msg = wrap($msg);

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

}


如果的代码有什么问题你可以帮我解决吗?Firefox中的Concole说Firefox can't establish a connection to the server at ws://localhost:12345/.


侃侃无极
浏览 894回答 3
3回答

暮色呼如

据我所知,Ratchet是目前最好的PHP WebSocket解决方案。而且由于它是开源的,你可以看到作者是如何使用PHP构建这个WebSocket解决方案的。
打开App,查看更多内容
随时随地看视频慕课网APP