-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsocket-server.php
More file actions
77 lines (64 loc) · 2.21 KB
/
socket-server.php
File metadata and controls
77 lines (64 loc) · 2.21 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php
error_reporting(E_ALL);
/* Allow the script to hang around waiting for connections. */
set_time_limit(0);
/* Turn on implicit output flushing so we see what we're getting
* as it comes in. */
ob_implicit_flush();
$address = 'localhost';
$port = 10000;
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
}
if (socket_bind($sock, $address, $port) === false) {
echo "socket_bind() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
if (socket_listen($sock, 5) === false) {
echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
do {
if (($msgsock = socket_accept($sock)) === false) {
echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
break;
}
/* Send instructions. */
$msg = "\nWelcome to the PHP Test Server. \n" .
"To quit, type 'quit'.\n";
socket_write($msgsock, $msg, strlen($msg));
do {
if (false !== ($buf = socket_read($msgsock, 2048))) {
if ($buf == 'quit') {
break;
}
else{
$values = explode("|", $buf);
if(count($values) == 2){
if(floatval($values[0]) != 0 && floatval($values[1]) != 0){
$conn = mysqli_connect('localhost', 'root', 'root', 'test');
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO test '.
'(Sensor, Val) '.
'VALUES ('. $values[0] .', '. $values[1] .')';
$retval = mysqli_query( $conn, $sql );
if(! $retval )
{
die('SQL QUERY NOT VALID.' . mysql_error());
}
error_log("SAVED");
mysqli_close($conn);
}
}
$msg = "\nOK\n";
socket_write($msgsock, $msg, strlen($msg));
error_log("CLIENT:" . $buf, 0);
}
}
} while (true);
socket_close($msgsock);
break;
} while (true);
socket_close($sock);
?>