<?php
error_reporting(E_ALL);

set_time_limit(0);

ob_implicit_flush();

$address = '127.0.0.1';
$port = 1337;

if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) {
	echo "Не удалось создать сокет, причина: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_bind($sock, $address, $port) === false) {
	echo "Не удалось привязать сокет к адрресу, причина: " . socket_strerror(socket_last_error()) . "\n";
}

if (socket_listen($sock, 5) === false) {
	echo "Не удалось выполнить socket_listen(): причина: " . socket_strerror(socket_last_error($sock)) . "\n";
}

do {
	if (($msgsock = socket_accept($sock)) === false) {
		echo "Не удалось выполнить socket_accept(): причина: " . socket_strerror(socket_last_error($sock)) . "\n";
        break;
	}

	socket_write($msgsock, "Welcome", strlen("Welcome"));

	do {
		if (false === ($buf = socket_read($msgsock, 2048, PHP_NORMAL_READ))) {
			echo "не удалось прочитать сокет, причина: " . socket_strerror(socket_last_error($msgsock));
			break 2;
		}

		if (!$buf = trim($buf)) {
			continue;
		}

		if ($buf == 'exit') {
			break;
		}

		socket_write($msgsock, $buf . "\n", strlen($buf));
		echo $buf . "\n";
	} while (true);
	socket_close($msgsock);
} while (true);

socket_close($sock);