Android interview technical points: xmpp knowledge preparation Socket server termination, Android xmpp
The previous section has basically completed communication between the server and the client, but does not implement persistent connection communication. This section fixes the bug.
1. for client code writing, we need to enable a thread to wait for the server to send a message.
public void startServerReplyListener(final BufferedReader serverToClientMsg){new Thread(new Runnable() {@Overridepublic void run() {try {String responce;while ((responce=serverToClientMsg.readLine())!=null) {System.out.println(responce);}} catch (IOException e) {e.printStackTrace();}}}).start();}
2. server-side code writing is actually impossible for all servers to serve a single client. Then, as long as the client is connected, we will not connect the client again, so the code should be changed, use a while loop to loop together and wait for client connection
// Enter the blocking status, wait for the client to intervene, and return a socket object while (true) {client = socket. accept (); ManagerConnection (client );}
Then enable thread reply Information
Public void ManagerConnection (final Socket socket) {new Thread (new Runnable () {@ Overridepublic void run () {try {System. out. println ("client" + socket. hashCode () + "connected"); clientToServerMsg = new BufferedReader (new InputStreamReader (client. getInputStream (); serverToClientMsg = new BufferedWriter (new OutputStreamWriter (client. getOutputStream (); String readermsg; // one row reads the value while (readermsg = clientToServerMsg. r EadLine ())! = Null) {System. out. println (readermsg); System. out. println ("client" + socket. hashCode () + ":" + readermsg); serverToClientMsg. write ("server reply" + readermsg + "\ n"); serverToClientMsg. flush () ;}} catch (IOException e) {e. printStackTrace ();} finally {try {clientToServerMsg. close (); serverToClientMsg. close ();} catch (IOException e) {e. printStackTrace ();}}}}). start ();}
End
To be continued
Click to download source code