The previous article on the Android Network Programming Foundation, today wrote a simple chat program to share
The first is the service-side code:
1 PackageCom.jiao.socketdemo;2 3 ImportJava.io.BufferedReader;4 ImportJava.io.BufferedWriter;5 Importjava.io.IOException;6 ImportJava.io.InputStreamReader;7 ImportJava.io.OutputStreamWriter;8 ImportJava.net.ServerSocket;9 ImportJava.net.Socket;Ten One Public classChatserverextendsThread { A PrivateServerSocket Server =NULL; - Private Static Final intPORT = 5550; - Privatebufferedwriter writer; the PrivateBufferedReader Reader; - - PublicChatserver ()throwsIOException { - +Createsocket ();//Initialize Socket - } + A @Override at Public voidrun () { - - Socket client; - String txt; - - Try { in while(true) { - //Get reply message toClient =Responsesocket (); + while(true) { - //Accept Client Information theTXT =receivemsg (client); * $SYSTEM.OUT.PRINTLN ("Message sent by client:" +txt);Panax Notoginseng - sendmsg (client, txt); the + if(true) A Break; the } + closesocket (client); - } $}Catch(Exception e) { $ //Todo:handle Exception - } - the } - Wuyi //Close Connection the Private voidClosesocket (Socket client)throwsIOException { - reader.close (); Wu writer.close (); - client.close (); About $ } - - //encapsulate methods for sending messages - Private voidSENDMSG (socket socket, String MSG)throwsIOException { Awriter =NewBufferedWriter (NewOutputStreamWriter (Socket.getoutputstream ())); +Writer.write (MSG + "\ n")); the Writer.flush (); - } $ the //encapsulating methods for receiving messages the PrivateString receivemsg (Socket socket)throwsIOException { theReader =NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); theString txt =reader.readline (); - returntxt; in } the the //Accept Message About PrivateSocket Responsesocket ()throwsIOException { theSocket client =server.accept (); the returnclient; the } + - //Initialize Socket the Private voidCreatesocket ()throwsIOException {BayiServer =NewServerSocket (PORT, 100); the } the -}
The code to start the server is as follows:
1 // Create a chat server 2 New chatserver (); 3 // detects if the server is started and if not, starts the server 4 if NULL ) {5 chatserver.start (); 6 }
The following is the code for the client:
1 Packagecom.example.socketclient;2 3 ImportJava.io.BufferedReader;4 ImportJava.io.BufferedWriter;5 Importjava.io.IOException;6 ImportJava.io.InputStreamReader;7 ImportJava.io.OutputStreamWriter;8 ImportJava.net.Socket;9 Importjava.net.UnknownHostException;Ten Importandroid.app.Activity; One ImportAndroid.os.Bundle; A - Public classMainactivityextendsActivity { - Public Static intServer_port = 5550; the - @Override - protected voidonCreate (Bundle savedinstancestate) { - Super. OnCreate (savedinstancestate); + Setcontentview (r.layout.activity_main); - + NewThread () { A Public voidrun () { at message (); - } - }.start (); - } - - Private voidmessage () { in Try { -Socket client = Requestsocket ("This is the IP of the server", server_port); tosendmsg (client, "Client send"); +String txt =receivemsg (client); -SYSTEM.OUT.PRINTLN ("Server-side return data:" +txt); the}Catch(Exception e) { * $ }Panax Notoginseng }; - the //client Get Message Class + PrivateSocket Requestsocket (String host,intPortthrowsunknownhostexception, IOException { ASocket socket =NewSocket (host, port); the returnsocket; + } - $ //client sends message class $ Private voidSENDMSG (socket socket, String msg)throwsIOException { - //The message to be sent is written to buffer -BufferedWriter writer =NewBufferedWriter (NewOutputStreamWriter (Socket.getoutputstream ())); the //Format Conversion -Writer.write ("\ n", "") + "\ n" (msg.replace));Wuyi //Refresh, send the Writer.flush (); - } Wu - //Client Receives message About PrivateString receivemsg (Socket socket)throwsIOException { $ //write in read buffer//gets the received message into the data flow -BufferedReader reader =NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); - //reading a message into a string -String MSG =reader.readline (); A //returns a message as a string + returnMSG; the } - $}
Simple chat program based on Android network programming