socket和php搭建,如何在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/.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值