Created
February 14, 2018 14:17
-
-
Save marinsagovac/23e733059812b398db7a9b7386ffa30a to your computer and use it in GitHub Desktop.
PHP TCP Server example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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