Skip to content

Instantly share code, notes, and snippets.

@stojg
Created January 29, 2013 04:45
Show Gist options
  • Save stojg/4661880 to your computer and use it in GitHub Desktop.
Save stojg/4661880 to your computer and use it in GitHub Desktop.
<?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();
/* Get the port for the WWW service. */
$service_port = 10000;
/* Get the IP address for the target host. */
$address = gethostbyname('localhost');
$socket = stream_socket_server("udp://".$address.':'.$service_port, $errno, $errstr, STREAM_SERVER_BIND);
if(!$socket) {
die("$errstr ($errno)");
}
do {
$pkt = stream_socket_recvfrom($socket, 1, 0, $peer);
echo "$peer\n";
stream_socket_sendto($socket, date("D M j H:i:s Y\r\n"), 0, $peer);
} while ($pkt !== false);
<?php
error_reporting(E_ALL);
/* Get the port for the WWW service. */
$service_port = 10000;
/* Get the IP address for the target host. */
$address = gethostbyname('localhost');
/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
if ($socket === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
exit(1);
}
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
echo "socket_connect() failed.".PHP_EOL.'Reason: ('.$result.') ' . socket_strerror(socket_last_error($socket)) . PHP_EOL;
exit(1);
}
$message = 'Hello';
socket_write($socket, $message, strlen($message));
echo "Response:".PHP_EOL;
echo socket_read($socket, 2048);
socket_close($socket);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment