在Android问题中从套接字读取长字符串

时间:2017-03-01 08:27:34

标签: android inputstream serversocket

我从服务器通过套接字获取长字符串数据,并且存在读取问题。

数据大约为10 MB。

private String createSocketConnection() throws IOException {
            String result = "";

        {
            String host = ServiceUrlManager.socketIP;
            int port = ServiceUrlManager.socketPort;
            InetAddress address = InetAddress.getByName(host);
            socket = new Socket(address, port);
            socket.setSoTimeout(timeOut);
            Log.d(TAG, ":::::Socket Connection " + socket.isConnected());
            DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
            dataOutputStream.write(createMSG());  
            dataOutputStream.write(sockecData);
            dataOutputStream.flush();

        //Read data from server connection
            InputStream inputStream = socket.getInputStream();


            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte buffer[] = new byte[1024];
            for(int s; (s=inputStream.read(buffer)) != -1; )
            {
                baos.write(buffer, 0, s);

            }

            String data = ISOUtil.hexString(baos.toByteArray());
            result = data.substring(0, baos.toByteArray().length); // response message
            Log.d(TAG, "::::Response " + result);

        }
        return result;
    }

1 个答案:

答案 0 :(得分:0)

  BufferedReader in =
    new BufferedReader(
    new InputStreamReader(inputStream.getInputStream()));

    StringBuilder sb= new StringBuilder();
    while(br.readLine!=null){
        sb.append(br.readLine());
    }