How to read a Java stream before reaching a certain byte

My question is similar to this article But I will not send the packet length instead of the last 0 bytes

So I want to know how I will write the code

At present, I just use

this.socketIn = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
String line = this.socketIn.readLine();

If you send a packet when you send it, it will calculate the packet that has not arrived as a full read line, but it is incomplete and will mess up the whole protocol

In my protocol, each packet ends with 0 bytes (0x00) to determine the end of a single packet (if the packets are finally merged / stacked together)

So what I really need to do is continue to read the socket stream until 0x00 indicates that the packet has been completely made and ready for processing Of course, there is some kind of security (I think timeout is the best) to determine that the packet is garbage because it does not end in 0 bytes of a specific time frame, such as 5 seconds

What should I do?

P. S > I don't use the NiO framework. It's just a regular thread connecting sockets. I don't want to switch to NiO because it's difficult to inject data with a completely different global thread, which processes updates and sends specific updates to random users (not broadcasts)

This is what I have tried so far

String line = "";
    int read;
    long timeOut = System.currentTimeMillis();
    while(true) {
        read = this.socketIn.read();
        if (read == -1 || read == 0 || (System.currentTimeMillis()-timeOut) > 5000)
            break;
        line += read
    }

Solution

This is a sketch of the "slow client / denial of service" scenario using setsocketimeout

this.socket.setSoTimeout(5000);
BufferedReader br = new BufferedReader(
    new InputStreamReader(this.socket.getInputStream()));
StringBuilder sb = new StringBuilder();
try {
    int ch ;
    while ((ch == br.read()) != -1) {
        if (ch == 0) {
            String message = sb.toString();
            // process message
            sb.setLength(0);
        } else {
            sb.append((char) ch);
        }
    }
} catch (InterruptedioException ex) {
    System.err.println("timeout!"); 
    ...
} finally {
    br.close();
}

I think we can also create a second thread to achieve (cruel) socket timeout. If it detects that the reading thread does not get any data, it calls socket on the socket object close(). But considering the simpler setsotimeout () method, this is a heavyweight method

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>