0

I am just playing with PHP sockets for fun. I am trying to implement a messaging service. I've been able to connect multiple client to the server but I can't receive all of the messages that I'm expecting.

my server.php

<?php
set_time_limit(0);

$address = '127.0.0.1';

$port = 8000;

$server = socket_create(AF_INET, SOCK_STREAM, 0);
$bind = socket_bind($server, $address, $port);

$clients = [];
$i = 0;

socket_listen($server);

while(TRUE) {
  foreach($clients as $id => $client) {
    $input = socket_read($client, 1024);

    if($input) {
      echo $input."\r\n";

      socket_write($client, 'We got your message.');
    }
  }

  $clients[$i] = socket_accept($server);

  if($clients[$i]) {
    echo 'Connection established.'."\r\n";

    socket_write($clients[$i], 'Welcome to the server!');
    $i++;
  } else {
    unset($clients[$i]);
  }
}

my client.php

<?php
$host = '127.0.0.1';
$port = 8000;
$timeout = 3;

$server = socket_create(AF_INET, SOCK_STREAM, 0);
socket_connect($server, $host, $port);

//socket_write($socket, 'Hello');

$result = socket_read($server, 1024);

echo 'Reply From Server: '.$result."\r\n";
$i = 0;

while($i <= 5) {
  sleep(3);

  socket_write($server, 'Hi server! Im Client 1');

  $result = socket_read($server, 1024);

  echo 'Reply From Server: '.$result.' ';

  echo $i."\r\n";
  $i++;
}

socket_close($server);

And also I have a client2.php file which exactly same with client.php except socket_write($server, 'Hi server! Im Client 1'); this line. Instead is says Im Client 2.

What am I expecting is when I run these 3 from seperate terminal windows is something like this;

  • Connection established.
  • Hi server! Im Client 1
  • Connection established.
  • Hi server! Im Client 1
  • Hi server! Im Client 2
  • Hi server! Im Client 1
  • Hi server! Im Client 2
  • Hi server! Im Client 1
  • Hi server! Im Client 2
  • Hi server! Im Client 1
  • Hi server! Im Client 2
  • Hi server! Im Client 2

And there must be 3 seconds between each block if we think like I run both of 3 at the same time.

But instead I am getting this:

  • Connection established.
  • Hi server! Im Client 1
  • Connection established.
  • Hi server! Im Client 1
  • Hi server! Im Client 2

And another problem is clients should be terminated themselves but they're not. Their outputs are like following:

client.php

  • Reply From Server: Welcome to the server!
  • Reply From Server: We got your message. 0
  • Reply From Server: We got your message. 1

client2.php

  • Reply From Server: Welcome to the server!
  • Reply From Server: We got your message. 0

I was expecting exact number of messages but I can't get.

0 Answers0