我在 android 客户端从 php 服务器接收数据时遇到问题。Android 可以成功地将数据写入 php 服务器,服务器接受该数据,然后将响应发送回该客户端,但 android 不接受。它不会从Socket s = ss.accept()
这是我接收数据的 android 代码
public void run() {
Boolean end = false;
ServerSocket ss = serverSocket;
/*try {
ss = new ServerSocket(54546);
} catch (IOException e1) {
//TODO Auto-generated catch block
e1.printStackTrace();
}*/
while(!end){
//Server is waiting for client here, if needed
try {
Log.i("before accept", "yes");
Socket s = ss.accept();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
//PrintWriter output = new PrintWriter(s.getOutputStream(),true); //Autoflush
String st = input.readLine();
Log.d("Tcp Example", "From client: "+st);
//output.println("Good bye and thanks for all the fish :)");
}catch (IOException e) {
e.printStackTrace();
}
}
}
这是我的php代码
$host = "127.0.0.1";
$port = 54546;
set_time_limit(0);
$socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
//$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket\n");
/*if (!socket_connect($socket, $host, $port)) {
die('failed'.socket_strerror(socket_last_error($socket)));
}*/
if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
echo socket_strerror(socket_last_error($socket));
exit;
}
$result = socket_bind($socket, $host, $port) or die("Could not create socket\n");
$result = socket_listen($socket, 3) or die("Could not set up socket listener\n");
echo "\nbefore socket accept while loop\n";
$aaa = fopen("tesst.txt", "w");
while(true)
{
echo "\nbefore socket accept\n";
$spawn = socket_accept($socket) or die("Could not accept incoming connection\n");
echo "\nThe server is ready\n";
$input = socket_read($spawn, 1024) or die("Could not read input\n");
echo "Input recieved from $spawn : ".$input;
fwrite($aaa, $input);
$output = $input."\n";
$sent = socket_write($spawn, $output, strlen ($output)) or die("Could not write output\n");
echo "Output sent ".$sent;
socket_close($spawn);
}
fclose($aaa);
socket_close($socket);
echo "\nTerminating\n";
ss.accept()
不接受来自服务器的连接。