Jump to content

Help with Socket Servers


jmajeremy

Recommended Posts

I wanted to expand my PHP knowledge, so followed an online tutorial on creating sockets. Came up with this simple socket program:

 

#!/usr/bin/php

<?php

set_time_limit(;

$host = "127.0.0.1";
$port = 1234;
$command = "/usr/games/banner";
$msg = "Enter a string and get a banner!\nEnter \"END\" to quit.";

$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
$result = socket_bind($socket, $host, $port) or die("Could not bind socket\n");
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");
echo "Waiting for connections...\n";

$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
echo "Received connection request\n";

$output = $msg . "\n>>\t";
socket_write($spawn, $output, strlen($output)) or die("Could not write output\n");

do {
  $input = socket_read($spawn, 1024, 1) or die("Could not read input\n");
  if(trim($input) != "") {
    echo "Received input: $input\n";
    if(trim($input) == "END") {
      socket_close($spawn);
      break;
    } else {
      $output = $command . ' ' . trim($input);
      $output = `$output` . "\n\n>>\t";  // Note backticks, not single quotes
      echo $output;
      socket_write($spawn, $output, strlen($output)) or die("Could not write output\n");
      echo "Sent output\n";
    }
  }
} while(true);

socket_close($socket);
echo "Socket terminated\n";
?>

 

 

What I soon realized is that this

a) closes the socket for good so that no one else can use it

b) only one client can use it at a time

 

How can I set up a socket server that accepts multiple simultaneous connections, and doesn't actually stop accepting new connections, even after terminating the connection with the current client?

Link to comment
https://forums.phpfreaks.com/topic/199341-help-with-socket-servers/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.