[英]How to read NSData into clientside made in java
I create an iOS server using GCDAsyncSocket and Client is created using Java language. 我使用GCDAsyncSocket创建iOS服务器,并且使用Java语言创建客户端。 When I sent data in form of NSDAta it can be read by SocketTester(application for testing client connection) but it cannot be completely read at java end . 当我以NSDAta形式发送数据时,它可以被SocketTester(用于测试客户端连接的应用程序)读取,但无法在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();
}
}
*/
} }
I want to get data length sent through ios server.and create buffer accordingly.Can any one help me out? 我想获取通过ios服务器发送的数据长度并相应地创建缓冲区。有人可以帮帮我吗?
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();
}
}
I solved this using 我用解决了
public static byte[] readChunkedData(final InputStream stream, final int size) throws IOException {
byte[] buffer = new byte[size];
DataInputStream din = new DataInputStream(stream);
din.readFully(buffer);
return buffer;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.