Skip to content

Instantly share code, notes, and snippets.

@marinsagovac
Created February 14, 2018 14:17
Show Gist options
  • Save marinsagovac/23e733059812b398db7a9b7386ffa30a to your computer and use it in GitHub Desktop.
Save marinsagovac/23e733059812b398db7a9b7386ffa30a to your computer and use it in GitHub Desktop.
PHP TCP Server example
<?php
$serv=stream_socket_server("tcp://0.0.0.0:8000",$errno,$errstr) or die("create server failed");
$base = event_base_new();
$event = event_new();
function read_cb($socket, $flag, $base) {
fread($socket);
fwrite("hello world\n");
}
function accept_cb($socket, $flag, $base) {
$conn = stream_socket_accept($socket);
stream_set_blocking($conn, 0);
$event = event_new();
event_set($event, $conn, EV_READ | EV_PERSIST, 'read_cb'), $base);
event_base_set($event, $base);
event_add($event);
}
event_set($event, $socket, EV_READ | EV_PERSIST, 'accept_cb', $base);
event_base_set($event, $base);
event_add($event);
event_base_loop($base);
<?php
$serv=stream_socket_server("tcp://0.0.0.0:8000",$errno,?$errstr) or die("create server failed");
while(1) {
$conn = stream_socket_accept($serv);
if (pcntl_fork() == 0 ) {
$request = fread($conn);
//do some thing
//$response = “hello world”;
fwrite($response);
fclose($conn);
exit(0);
}
}
<?php
$serv=stream_socket_server("tcp://0.0.0.0:8000",$errno,$errstr) or die("create server failed");
for($i=0; $i < 32; $i ++) {
if (pcntl_fork() == 0 ) {
while(1) {
$conn = stream_socket_accept($serv);
if ($conn == false) continue;
$request = fread($conn); //do some thing
//$response = “hello world”;
fwrite($response);
fclose($conn);
} exit(0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment