我有一个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()
不接受来自服务器的连接。
答案 0 :(得分:0)
我们也不必为客户端做ss.accept()。客户端应使用connect()建立连接,服务器应该执行accept()。建立连接后,服务器应使用accept()返回的文件描述符向客户端发送数据或从客户端接收数据。另一方面,客户端不需要进行任何接受,只需调用recv()来检索接收的数据。
因此,如果Android代码是客户端,那么它应该对PHP服务器执行connect()调用 - connect()调用将获取IP地址和端口号(54546)。通过成功的connect()调用,PHP上的accept()将返回。