2017-06-06 15 views
0

我使用GCDAsyncSocket創建iOS服務器,客戶端使用Java語言創建。當我以NSDAta的形式發送數據時,它可以被SocketTester(用於測試客戶端連接的應用程序)讀取,但它不能在java端完全讀取。如何讀NSData到客戶端在java中製作

static void recorderServerClient() throws IOException{ 
    int port =9892; 
     clientSocket = new Socket("localhost", port); 
     System.out.print("Connected to localhost"+port); 

     while (true){ 
     InputStream inputStream = clientSocket.getInputStream(); 
     try { 
      Thread.sleep(3000); 
      } 
     catch (InterruptedException e) { 
      e.printStackTrace(); 
     }/*fetch data with help of output stream and write it with help of PrintWriter */ 
     PrintWriter printWriterObj = new PrintWriter(clientSocket.getOutputStream()); 
      printWriterObj.println(); 
      printWriterObj.flush(); 
      /*created an array for now static and assign some memory */    byte[] buffer = new byte[1000000]; 
      int read; 
      while((read = inputStream.read(buffer)) != -1) { 
       String output = new String(buffer, 0, read); 
       System.out.print(output); 
       System.out.flush(); 
      } 
     } 
     */ 

}

我想要得到的數據長度通過IOS發送server.and創建緩衝區accordingly.Can任何一個可以幫助我嗎?

+0

你看到了什麼問題?看起來你缺少Socket.accept()調用? –

+0

我無法通過java的readInt方法讀取數據長度。 – Ruby

回答

0
import java.io.*; 
import java.net.Socket; 

public class SocketDemo { 
    public static void main(String args[]) throws Exception { 

     Socket socket = new Socket("localhost", 2100); 
     System.out.println("Connected"); 

     DataInputStream ins = new DataInputStream(socket.getInputStream()); 
     DataOutputStream out = new DataOutputStream(socket.getOutputStream()); 
     System.out.println("opened OutputStreams"); 

     System.out.println(readResponse(ins)); 
     Thread.sleep(100); 
     out.write("ss 1\n".getBytes());//send command 
     out.flush(); 
     System.out.println("sent command"); 
     Thread.sleep(3000);//important to wait for the server to response 
     System.out.println(readResponse(ins)); 
     socket.close(); 
     System.out.println("Connection to the server closed"); 
    } 

    private static String readResponse(InputStream in) throws IOException { 
     byte[] buf = new byte[1024];//1k 
     StringBuilder sb = new StringBuilder(); 
     while (in.available() > 0) {//server is waiting for client once it sent all data 
      int pos = in.read(buf); 
      String s = new String(buf, 0, pos); 
      sb.append(s); 
      //System.out.println("reading data..." + pos + " s>>>" + s.getBytes() + "available?" + ins.available()); 
      //System.out.print(pos + " ? " + (char) pos); 
     } 
     return sb.toString(); 
    } 
} 
+0

對不起,這段代碼在我的情況下不起作用。它只是掛起我的系統。我只是想要一個可以連接到端口並完全讀取數據的客戶端 – Ruby

+0

正如我所說的演示。當你說它掛起你的系統。你什麼意思?你如何連接到服務器插座?這是你如何測試這個演示。運行該程序,它會顯示「服務器已啓動並正在監聽9892」。然後打開另一個終端並輸入「telnet localhost 9892」。鍵入一個數字開始,然後它會回顯你輸入的內容。如果你瞭解代碼,這應該是顯而易見的。 –

+0

我已經使用GCDSyncSocket類在iOS中編寫服務器。只有客戶端部分必須在java端完成。檢查完代碼後,它不適用於我。它只是掛我的系統3次。沒有光標移動。每個正在運行的應用程序只是掛起。 – Ruby