Skip to content

Commit f999587

Browse files
committed
create tcp socket connection
1 parent 61489e0 commit f999587

File tree

1 file changed

+76
-3
lines changed

1 file changed

+76
-3
lines changed

server.php

Lines changed: 76 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,84 @@
11
<?php
2+
23
class Server {
3-
public function __construct()
4+
5+
private Socket $socket;
6+
7+
public function __construct(private string $host, private string $port)
8+
{
9+
$this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
10+
socket_bind($this->socket, $this->host, (int) $this->port);
11+
}
12+
13+
/**
14+
* @throws Exception
15+
*/
16+
public function listen(): Socket
417
{
5-
echo 'Hello, world!';
18+
socket_listen($this->socket);
19+
return socket_accept($this->socket);
620
}
721

22+
/**
23+
* @throws Exception
24+
*/
25+
public function read(Socket $connection): string
26+
{
27+
// read any data coming from established tcp socket connection
28+
$data = socket_read($connection, 1024);
29+
30+
if (false === $data) {
31+
throw new Exception('Failed to read incoming tcp connection data');
32+
}
33+
34+
return $data;
35+
}
36+
}
37+
38+
$args = $_SERVER['argv'];
39+
40+
$host = '127.0.0.1';
41+
$port = '8000';
42+
43+
$argArray = [];
44+
45+
// try to parse command line arguments for --host and --port
46+
47+
if (count($args) > 1) {
48+
parse_str($args[1], $argArray);
49+
}
50+
51+
if (count($args) > 2) {
52+
parse_str($args[1], $argArray);
53+
parse_str($args[2], $argArray);
854
}
955

56+
// overwrite with command line arguments if any
57+
$host = $argArray['--host'] ?? $host;
58+
$port = $argArray['--port'] ?? $port;
59+
1060
// Run things
11-
$server = new Server();
61+
$server = new Server($host, $port);
62+
63+
$message = sprintf('Listening on %s:%s', $host, $port);
64+
65+
66+
while (true) {
67+
$tcp = $server->listen();
68+
69+
try {
70+
$data = $server->read($tcp);
71+
72+
if (strlen($data) > 0) {
73+
echo sprintf('%s: Request received [%s]', time(), $data);
74+
75+
socket_write($tcp, $data);
76+
}
77+
78+
socket_close($tcp);
79+
} catch (Exception $e) {
80+
echo $e->getMessage();
81+
}
82+
}
83+
84+

0 commit comments

Comments
 (0)