Created
December 21, 2020 11:40
-
-
Save askaaqib/58668a0a4520f755bfcbc3da7c7cfd74 to your computer and use it in GitHub Desktop.
P2P Server PHP - Storing Database message
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 | |
require "../../vendor/autoload.php"; | |
// set some variables | |
$host = "127.0.0.1"; | |
$port = 25002; | |
// don't timeout! | |
set_time_limit(0); | |
// create socket | |
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n"); | |
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1); | |
// bind socket to port | |
$result = socket_bind($socket, $host, $port) or die("Could not bind to socket\n"); | |
// start listening for connections | |
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n"); | |
$x = 1; | |
while($x <= 100){ | |
// accept incoming connections | |
// spawn another socket to handle communication | |
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n"); | |
// read client input | |
$input = socket_read($spawn, 1024) or die("Could not read input\n"); | |
// clean up input string | |
$input = trim($input); | |
echo "Client Message : ".$input; | |
// reverse client input and send back | |
$output = strrev($input) . "\n"; | |
socket_write($spawn, $spawn, strlen ($output)) or die("Could not write output\n"); | |
// close sockets | |
echo "\n"; | |
// echo "<pre>"; | |
// INsert into db | |
$dbCreds = new \Comely\Database\Server\DbCredentials("mysql"); | |
$dbCreds->credentials("root","asd2020")->server("localhost",3306)->database("p2p"); | |
try { | |
$db = new \Comely\Database\Database($dbCreds); | |
} catch (\Comely\Database\Exception\DbConnectionException $e) { | |
print_r($e); | |
} | |
$db = new \Comely\Database\Database($dbCreds); | |
$db->query()->table("messages")->insert(["input"=>$input]); | |
// $db->query()->table("peer")->insert(["peer"=>$spawn]); | |
socket_close($spawn); | |
$x++; | |
} | |
socket_close($socket); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment