2012-10-29 68 views
0

我在php中打開一個套接字併發送消息。當我嘗試在此套接字中讀取Java中的消息時,連接已建立,但消息爲空?PHP套接字消息null

任何幫助? Cannot read response from Java socket server using PHP client這是我遇到的同樣的問題,但我確實在郵件中加入了\ n。

// variables 
     $host = gethostbyname('localhost'); 
     $port = 4444; 
     $message = $host." list\n\0"; 

     // create socket 
     if (!($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))) { 
      $errorcode = socket_last_error(); 
      $errormsg = socket_strerror($errorcode); 
      die("Couldn't create socket: [$errorcode] $errormsg \n"); 
     } 
     echo "Socket created!\n"; 

     // connect 
     if (!socket_connect($sock, $host, $port)) { 
      $errorcode = socket_last_error(); 
      $errormsg = socket_strerror($errorcode); 
      die("Couldn't connect: [$errorcode] $errormsg \n"); 
     } 
     echo "Connection established!\n"; 
     echo $message; 
     $length = strlen($message); 
     // get room info - send message 
     while(true){ 
      $sent=sock_write($sock, $message, 1024); 
      if ($sent===false) { 
       $errorcode = socket_last_error(); 
       $errormsg = socket_strerror($errorcode); 
       die("Couldn't send data: [$errorcode] $errormsg \n"); 
      } 
      // Check if the entire message has been sented 
       if ($sent < $length) { 

       // If not sent the entire message. 
       // Get the part of the message that has not yet been sented as message 
       $st = substr($msg, $sent); 
       $message= $st; 

       // Get the length of the not sented part 
       $length -= $sent; 

      } else { 

       break; 
      } 


     }   

     echo "Message sent!\n"; 

和Java方面

while (true) { 

     try { 

      socket = new ServerSocket(4444); 


     } catch (UnknownHostException e) { 
      System.err.println("Dont know about host: localhost."); 
      System.exit(1); 
     } catch (IOException e) { 
      System.err.println("Couldn't get I/O for the connection to localhost"); 
      System.exit(1); 
     } 

     try { 

      clientSocket = socket.accept(); 
      System.out.printf("Connected!\n"); 

     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     try { 

      PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); //object to send data 
      BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); //object to read data 
      String inputLine, outputLine; 
      inputLine = in.readLine(); //read data 

      System.out.println(inputLine); 

Java代碼的運作就像一個網關服務器。

+1

你能否提供一些細節?代碼的發送和接收部分將非常有幫助。 – Kosi2801

+0

您將需要提供您正在使用的服務器和客戶端類代碼。否則我們將無法爲您提供幫助 –

回答

0
$sent=sock_write($sock, $message, 1024); 

這應該是

$sent=sock_write($sock, $message, $length); 

甚至$長度-1作爲Java是不感興趣的尾隨空。

+0

這也不是問題 –