Reading Socket Inputstream Without End Of Transmission Character?

时间:2016-04-12 00:50:20

标签: java android sockets inputstream blocking

I'm trying to read the data back from a server program that I didn't write. The server program doesn't send any kind of end of transmission character and it doesn't close the socket once it sends a response. There is a button I can press on the server to close the connection manually and if I leave a little bit of a timeout on the (android)client side so I have time to press it, I do get the data from the server into my client app. Otherwise it just eventually times out and I get no response. Since I can't control the protocol on the server side how can I close the connection and get the response from the server? Thanks for any help.

            cSocket.setSoTimeout(timeOut);  

            cOut = new PrintWriter(cSocket.getOutputStream(), true);

            cOut.println(msgIn);       

            cIn = new BufferedReader(new InputStreamReader(
                cSocket.getInputStream()));   

           int intTest;
           while ((intTest = cSocket.getInputStream().read()) != -1) {
           System.out.println(cIn.readLine());  

Message from the server looks like this: char(60)...char(62)char(60)...char(62)char(60)...char(62)char(60)...char(62)

... is random data inside the chars doesn't duplicate.

*Final edit

Got it working like this:

int c;
int intCount = 0;
StringBuilder response= new StringBuilder();
while ((c = cIn.read()) != -1) {

    response.append( (char)c ) ; 

       if (c == 62) {
       intCount = intCount + 1;        
       }
       if (intCount >=4) {
           cSocket.close();
           String result = response.toString();
           System.out.println(result);
           break;
       }

}

1 个答案:

答案 0 :(得分:1)

while ((intTest = cSocket.getInputStream().read()) != -1) {
    System.out.println(cIn.readLine());  

这没有任何意义。仅仅因为你读了一个字节并不意味着你可以阅读另一行,并且你丢弃了你读过的字节。它应该是:

while ((intTest = cSocket.getInputStream().read()) != -1) {
       System.out.println(intTest);  

intTest是输入字节的可怜名称。没有'测试'关于它。我会称之为ib