Pre-Knowledge:
One, Android each client is divided into two threads:
1. Main thread: Responsible for generating the main interface, and responding to user actions, and the user input data written to the socket corresponding output stream.
2. Sub-thread: Responsible for reading the data sent from the server, and display to the program interface.
Second, handler message transmission mechanism
(i) The two roles of handler:
1. Send the message in the newly-started thread.
2. Get and process messages in the main thread.
(ii) Several components related to handler:
The 1.message:handler receives and processes the message object.
2.Looper: Each thread can have only one Looper.
In the main thread (UI thread), the system has initialized a Looper object, so only handler appears in the main thread, and Looper is not present.
In a child thread, the program ape needs to create itself a Looper, in the Order of: Looper.prepare (); Handler handler=new Handler () {...}; Looper.loop ();
where the prepare () method guarantees that there is at most one Looper object per thread, the loop () method continuously extracts the message from the MessageQueue with a dead loop and assigns the extracted message to the handler corresponding to the message for processing.
3.MessageQueue: Message Queuing, a FIFO-first way to manage messages.
Three relations:
MessageQueue is a looper to manage the message, that is, Looper is given the first-in-one function of MessageQueue.
Handler is the processing of the message.
Iii. on the role of BufferedReader
1. First it is a buffer, whereas the Rendline () method: The entire line string is passed in when the newline character is read.
2. This thing is used only when the socket (the server passes to the client) passes the data out to the client, and its purpose is to convert the data passed by the server (S.getinputstream ()) to a string stream via InputStreamReader. Convenient to the back handler to deal with it!
Organize the idea of multi-threaded client:
1.Activity (UI meets the design
+ Processing of messages from the server handler
+ Define a child thread that communicates with the server (Clientthread clientthread=new clientthread (handler))
+ Start the Clientthread thread (clientthread). Start ();
+ listeners (such as sending messages)
);
2. Child thread Clientthread
(defines a handler that sends information to the UI thread and two handler that receive information about the UI thread
+run () method {link Server IP and port
+ Get information from the server Br=new bufferedreder (new InputStreamReader (S.getinputstream ()));
+ Start a sub-thread to read data from the server (including tags and incoming message, then send to handler)
}
+ initializes the Looper.prepare () for the current thread;
+ Create Handler object: Cheng information from UI line and write to server in network
+looper.loop ();
);