我正在尝试为messenger编写PHP套接字服务器。这是我的PHP代码:
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, 100) === false) {
echo "socket_listen() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
}
//clients array
$clients = array();
do {
$read = array();
$read[] = $sock;
$read = array_merge($read, $clients);
// Set up a blocking call to socket_select
if (@socket_select($read, $write = NULL, $except = NULL, $tv_sec = 100) < 1) {
// SocketServer::debug("Problem blocking socket_select?");
continue;
}
// Handle new Connections
if (in_array($sock, $read)) {
if (($msgsock = socket_accept($sock)) === false) {
echo "socket_accept() failed: reason: " . socket_strerror(socket_last_error($sock)) . "\n";
break;
}
$clients[] = $msgsock;
$key = array_keys($clients, $msgsock);
/* Enviar instrucciones. */
$msg = "\nWelcome to the PHP Test Server. \n" .
"Client key number: {$key[0]}\n" .
"To quit, type 'quit'. To shut down the server type 'shutdown'.\n";
socket_write($msgsock, $msg, strlen($msg));
}
// Handle Input
foreach ($clients as $key => $client) { // for each client
if (in_array($client, $read)) {
if (false === ($buf = socket_read($client, 4096, PHP_NORMAL_READ))) {
echo "socket_read() failed: reason: " . socket_strerror(socket_last_error($client)) . "\n";
break 2;
}
if (!$buf = trim($buf)) {
continue;
}
if ($buf == 'quit') {
unset($clients[$key]);
socket_close($client);
break;
}
if ($buf == 'shutdown') {
socket_close($client);
break 2;
}
$talkback = "Client {$key}: Said: '$buf'.\n";
socket_write($client, $talkback, strlen($talkback));
echo "$buf\n";
}
}
} while (true);
当我通过终端连接时,效果很好。但是当试图通过Android连接拒绝。并向我显示错误:socket_read() failed: reason: Connection reset by peer
。
这是我的Android代码:
InetAddress serverAddr;
try {
serverAddr = InetAddress.getByName(dstAddress);
} catch (UnknownHostException e) {
e.printStackTrace();
}
try {
socket = new Socket(serverAddr, SERVERPORT);
socket.setSendBufferSize(10000);
commThread.setClientSocket(socket);
cmThread = new Thread(commThread);
connected = true;
} catch (Exception e) {
connected = false;
}
我必须做些什么才能解决这个问题。 谢谢!