2013-09-24 48 views
0

我有一個Android客戶端從PHP服務器接收數據的問題。 Android可以成功地將數據寫入到php服務器,服務器接受該數據,然後發送回該客戶端的響應,但android不接受。它不會從向前Socket s = ss.accept()Android套接字無法接收來自PHP服務器的數據

移動這裏是我的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

我們不必爲客戶端做ss.accept()。客戶端應該使用connect()建立連接,服務器應該接受accept()。建立連接後,服務器應使用從accept()返回的文件描述符來向客戶端發送數據或從客戶端接收數據。另一方面,客戶端不需要做任何接受,它應該簡單地調用recv()來檢索接收到的數據。因此,如果Android代碼是客戶端,那麼它應該對PHP服務器執行connect()調用 - connect()調用將使用IP地址和端口號(54546)。通過connect()調用,PHP上的accept()將返回。

相關問題