2017-06-06 14 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