Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Created September 4, 2018 01:02
Show Gist options
  • Save miguelmota/47e0e04865fb656996377c2ec85ed2d4 to your computer and use it in GitHub Desktop.
Save miguelmota/47e0e04865fb656996377c2ec85ed2d4 to your computer and use it in GitHub Desktop.
PHP TCP server example
<?php
$host = "127.0.0.1";
$port = 3000;
set_time_limit(0);
$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 to socket\n");
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");
while(true) {
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
$input = socket_read($spawn, 1024) or die("Could not read input\n");
echo $input.PHP_EOL;
$output = $input . "\n";
socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");
socket_close($spawn);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment