recently doing Socket long connection, there are some problems, there is no good idea, hope to get an answer.
now I only do BIO, that is, the traditional IO, blocking operation, in order to learn. So I didn"t use NIO,AIO and so on.
1. The client starts two threads, one listens for console input, and starts another thread in this thread to listen for data returned by the server
new Thread(new ReadContentTask(bufferedReader)).start();//
bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String content = "";
while (!(content = bufferedReader.readLine()).equals("exit")) {
//\nreadline()\n
bufferedWriter.write(content + "\n");
bufferedWriter.flush();
}
listener server returns data thread code:
@Override
public void run() {
try{
String content = "";
while((content = bufferedReader.readLine())!=null){
System.out.println(content);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try{
bufferedReader.close();
}catch (Exception e2){
e2.printStackTrace();
}
}
}
server code:
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));//
bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));//
String lineString = "";
//new Thread(new ReceiveHeart(socket)).start(); //
while (!(lineString = bufferedReader.readLine()).equals("quit")) {
System.out.println(":" + lineString);
bufferedWriter.write(":" + lineString + "\n");
bufferedWriter.flush();
}
the question now is that I want to make a heartbeat bag, how to design it?
my idea is that, for example, the client starts another thread and sends an array of "x" bytes to the server every 30 seconds. After receiving it, the server returns "x" to the client and resets the heartbeat time. If the client does not receive the data returned by the server within a certain period of time, it determines that the heartbeat is broken and starts a new thread reconnection.
the design I am doing now is that the client sends a byte of data to the server, and the data written by the client on the console is also sent to the server. How can the inputstream, server of the same socket tell whether the message received is a heartbeat message or a normal message?