The previous server and client simply made a simple communication operation: After the server received the client connection
The server outputs a string to the client, and the client simply reads the server string and exits
Clients in real-world applications may need to maintain long-time communication with the server, which is the server
It is necessary to constantly read the client's data and write data to the client, and the client needs constant
Reads the server and writes data to the database.
When the data is read using the traditional BufferedReader ReadLine method, when the method returns successfully, the thread
is blocked, the program cannot continue. Therefore, the server should open a thread for each socket, each thread
is responsible for communicating with a client.
Server-side:
Class Serverthread implements Runnable {Socket s; BufferedReader br;public Serverthread (Socket s) throws IOException {super (); THIS.S = s;br = new BufferedReader (New INPUTST Reamreader (S.getinputstream ()));} @Overridepublic void Run () {String content = null;try {while (content = Readfromclient ())! = null) {for (Socket S:multi Threadserver.sockets) {OutputStream Os;os = S.getoutputstream (); Os.write ((content + "\ n"). GetBytes ("Utf-8"));}}} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} Private String readfromclient () {try {return br.readline ();} catch (IOException e) {//TODO auto-generated catch BLOCKE.PR Intstacktrace ();} return null;}} public class Multithreadserver {public static arraylist<socket> sockets = new arraylist<socket> ();p ublic static void Main (string[] args) throws IOException {ServerSocket ss = new ServerSocket (45623); while (true) {Socket s = ss. Accept (); Sockets.add (s); new Thread (New Serverthread (s)). Start ();}}
Each time the client socket connects to the ServerSocket, the
The program adds the corresponding socket to the collection and opens a thread for the socket that handles the socket's
All communication transactions.
Client:
Multiclient:
public class Multithreadclient extends Activity {EditText input; TextView Show; Button send; Handler Handler; Clientthread clientthread; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_client_thread); input = (EditText) Findviewbyid (R.id.input); Show = (TextView) Findviewbyid (r.id.show); send = (Button) Findviewbyid (r.id.send); handler = new Handler () {@ overridepublic void Handlemessage (Message msg) {//If the message is from a child thread if (msg.what = = 0x123) {//Append the read to the text show.append ("\ n" + M Sg.obj.toString ());}}; Clientthread = new Clientthread (handler);//client initiates Clientthread thread creates a network connection, reads data from the server new Thread (Clientthread). Start (); Send.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {//When the user presses the Send button, the data entered by the user is encapsulated as a message , and then send the handlermessage msg = new Message () to the child thread, msg.what = 0x345;msg.obj = Input.gettext (). toString (); ClientThread.revHandler.sendMessage (msg); Input.settext ("");}});}}
Clientthread:
public class Clientthread implements Runnable {Private Socket s;//defines the handler object that sends messages to the UI thread. The private Handler handler;//defines the Handler object that receives the message for the UI thread. Public Handler revhandler;//The stream object used by the socket that the thread handles BufferedReader Br;o Utputstream os;public clientthread (Handler Handler) {super (); this.handler = Handler;} @Overridepublic void Run () {try {s = new Socket ("192.168.3.12", 45623); br = new BufferedReader (New InputStreamReader (s.get InputStream ())); OS = S.getoutputstream ();//Start a child thread new thread () {public void run () {String content = null;//continuously reads the socket input stream The contents of the try {while (content = Br.readline ()) = null) {//each time the data from the server is read, the Send Message Notifier interface displays the data message msg = new Message (); msg.what = 0x123;msg.obj = Content;handler.sendmessage (msg);}} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}};}. Start ();//Initialize Looperlooper.prepare () for current thread,//Create Revhandler Object revhandler = new Handler () {@Overridepublic void Handlemessage (Message msg) {//receives the user input data in the UI thread if (msg.what = = 0x345) {//writes the user's input in the text box to the network try {OS.WRIte ((msg.obj.toString () + "\ r \ n"). GetBytes ("Utf-8");} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}; Looper.loop ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}
Android------Join multithreading for socket communication