Show code - CODE/PHP/phpmud.php


#!/usr/bin/php
<?php
# Php isnt just for websites. ;)
# Php needs to be compiled with fctnl and readline both enabled
# for this script to run (among other things, but those were what
# I needed to configure in - i.e. sockets are needed).
error_reporting (E_ALL);
class MUDConnection {
function create_socket () {
$this->socket = socket_create (AF_INET, SOCK_STREAM, 0);
if ($this->socket < 0) {
echo "Failed creating socket: " . socket_strerror($this->socket) . "\n";
die();
} else {
echo "Socket created\n";
}
}
function connect ($socket, $address, $port) {
$this->connection = socket_connect ($this->socket, $address, $port);
if ($this->connection < 0) {
echo "Error connecting: " . socket_strerror($this->connection) . "\n";
die();
} else {
echo "Connected to " . $address . "\n";
$this->connected = True;
}
}
function mud_read () {
$this->out = socket_read($this->socket, 2048);
}
function mud_write ($txt) {
socket_write($this->socket, $txt, strlen($txt));
}
function kill_me () {
$pid = $this->pid;
$mypid = $this->mypid;
socket_close ($this->socket);
$this->connected = False;
print ("Bye...\n");
# Hmm... script doesn't die like I had hoped it would.
# There has to be a better way to kill this script.
shell_exec("kill -9 $pid\n"); #;kill -9 $mypid\n");
}
}
if (!function_exists('readline')) {
# In case readline's just not an option.
function readline() {
$fp=fopen("php://stdin", "r");
$in=fgets($fp,4094);
fclose($fp);
return ereg_replace("\n", "", $in);
}
function readline_add_history($str) {}
}
$con = new MUDConnection;
$con->create_socket();
$con->connect($con->socket, "atrocity.org", 6715);
$keystroke = False;
$con->mypid=$mypid = getmypid();
$con->pid=$pid = pcntl_fork();
if ($pid == -1) {
die("could not fork");
} else if ($pid) {
do {
$con->mud_read();
print $con->out;
flush();
} while ($con->connected);
} else {
do {
$keystroke = readline() . "\n";
if ($keystroke) {
if ($keystroke == "/quit\n") {
$con->kill_me();
} else {
$con->mud_write($keystroke."\n" );
readline_add_history(ereg_replace("\n", "", $keystroke));
}
}
flush();
} while ($con->connected);
}
?>