Service-Side code:
The thread class that handles each thread's communication is public class Serverthread implements runnable{//defines the socketsocket s = null;//that the current thread handles The input stream corresponding to the socket processed by the thread bufferedreader br = Null;public serverthread (socket s) throws IOEXCEPTION{THIS.S = s;// Initialize the socket corresponding to the input stream br = new BufferedReader (New InputStreamReader (S.getinputstream (), "Utf-8")); ②}public void Run () {try{string content = null;//uses loops to continuously read the data sent by the client from the socket while (content = Readfromclient ())! = null) {//Traverse each socket,//in the socketlist to send the read content to each socket once for (socket s:myserver.socketlist) {OutputStream OS = S.getoutputstream (); Os.write ((content + "\ n"). GetBytes ("Utf-8");}}} catch (IOException e) {e.printstacktrace ();}} Defines the method for reading client data private String readfromclient () {Try{return br.readline ();} If you catch an exception, the client that corresponds to the socket has closed catch (IOException e) {//delete the socket. MyServer.socketList.remove (s); ①}return null;}}
Public class myserver{//defines the arraylistpublic static arraylist<socket> socketlist= new arraylist< that holds all sockets Socket> (); public static void Main (string[] args) throws IOException {serversocket ss = new ServerSocket (30000); while (true) {// This line of code will block and will wait for someone else's connection to the socket S = ss.accept (); Socketlist.add (s);//Whenever a client connects, start a serverthread thread for the client service new thread (new Serverthread (s)). Start ();}}
Client code:
public class Clientthread implements Runnable{private Socket s;//defines the Handler object that sends messages to the UI thread private Handler handler;// The Handler object that defines the message that receives the UI thread public Handler revhandler;//the input stream corresponding to the socket processed by the thread bufferedreader br = Null;outputstream OS = null; Public Clientthread (Handler Handler) {this.handler = Handler;} public void Run () {try{s = new Socket ("192.168.1.88", 30000); br = new BufferedReader (New InputStreamReader ( S.getinputstream ())); OS = S.getoutputstream ();//Start a sub thread to read the server response data New Thread () {@Overridepublic void run () {String Content = null;//continuously reads the contents of the socket input stream. 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 = 0x12 3;msg.obj = Content;handler.sendmessage (msg);}} catch (IOException e) {e.printstacktrace ();}}}. Start ();//Initialize Looperlooper.prepare () for current thread,//Create Revhandler Object revhandler = new Handler () {@Overridepublic void Handlemessage (Message msg) {//receives the data entered by the user 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 (Exception e) {e.printstacktrace ();}}}};/ /start Looperlooper.loop ();} catch (Sockettimeoutexception E1) {System.out.println ("Network connection timed out!! ");} catch (Exception e) {e.printstacktrace ();}}}
The public class Multithreadclient extends activity{//defines two text boxes on the interface edittext input; TextView show;//defines a button on the interface buttons send; Handler handler;//defines a child thread Clientthread clientthread that communicates with the server; @Overridepublic void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.main); input = (EditText) Findviewbyid (r.id.input); send = (Button) Findviewbyid (r.id.send); show = (TextView) Findviewbyid (r.id.show); handler = new Handler ()//①{@ overridepublic void Handlemessage (Message msg) {//If the message is from a child thread if (msg.what = = 0x123) {//Append read content to the text box show.append ("\ n" + Msg.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) {try{//When the user presses the Send button, The data entered by the user is encapsulated into message,//and then sent to the child thread by handlermessage msg = new Message (); msg.what = 0x345;msg.obj = Input.gettext (). ToString () ; ClientThread.revHandler.sendMessage (msg);//emptying the input text box Input.settext ("");} catch (Exception e) {e.printstacktrace ();}}});}}
A client sends data to the server, and the server forwards the data to the connected client demo