-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket_server.php
64 lines (48 loc) · 1.65 KB
/
socket_server.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
// Check php sockets extention
if (!extension_loaded("sockets")) {
throw new Exception("failed to load php 'sockets' extentions");
}
// Set the IP address and port number
$address = '127.0.0.1';
$port = 12345;
$connectionCount = 5;
$recivedDataLength = 1024;
// Create a TCP/IP socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
exit();
}
// Bind the socket to the address and port
$result = socket_bind($socket, $address, $port);
if ($result === false) {
echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
exit();
}
// Start listening for incoming connections
$result = socket_listen($socket, $connectionCount);
if ($result === false) {
echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
exit();
}
echo "Server listening on $address:$port\n";
// Accept incoming connections
while (true) {
$client_socket = socket_accept($socket);
if ($client_socket === false) {
echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($socket)) . "\n";
break;
}
// Read data from the client
$input = socket_read($client_socket, $recivedDataLength);
print("request data : $input \n");
// Process the received data
$output = "Server received : " . trim($input) . "\n";
// Send response back to the client
socket_write($client_socket, $output, strlen($output));
// Close the client socket
socket_close($client_socket);
}
// Close the server socket
socket_close($socket);