开发者

Only one connection at a time in phpwebsocket

开发者 https://www.devze.com 2023-03-11 21:27 出处:网络
I am playing with phpwebsocket. Is there a way to have only one user connected at a time? If a second user tries to connect they should be automatically disconnected and if the first user is idle for

I am playing with phpwebsocket. Is there a way to have only one user connected at a time?

If a second user tries to connect they should be automatically disconnected and if the first user is idle for a given amount of time he should be disconnected to allow space for a new user.

Is this possible - and if开发者_如何学Go so, does anyone know how?


It's possible to limit usercount to one user, of course. You have to look at usercount and decide to accept or not new connections. In code it looks like this:

if($socket==$master){
  $client=socket_accept($master);
  if($client<0){ console("socket_accept() failed"); continue; }
  else{ connect($client); }
}

You can make a further if statement to check, if usercount is 0, so you accept connection:

if($socket==$master){
  if(count($users) == 0){
    $client=socket_accept($master);
    if($client<0){ console("socket_accept() failed"); continue; }
    else{ connect($client); }
  }
}

To disconnect a silent user, i would refresh timestamp of user evertime the user sends a message to server. Now the only thing to do is to check, if diffence between users timestamp and current time is higher then your disconnect time. If so, kick him :)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号