Use Android Network Programming to Implement simple chat rooms

Source: Internet
Author: User
Tags connect socket

In Java, we can use socket programming to implement chat rooms. This is also true for Android, because Android fully supports TCP and UDP network communication APIs of JDK. We can use serversocket and socket to establish network communication based on TCP/IP protocol, or use datagramsocket, datagrampacket, and multicastsocket to establish network communication based on UDP protocol. The following is a simple chat room. The server side is fully implemented using Java code and has nothing to do with Android. The client side is implemented using Android applications.

The server constantly reads information from the client and sends the information to each client connected to the server in real time. Each client can send messages to the server and continuously receive messages from the server, and display the message on the interface. In this way, the real-time chat function between the client and the client is realized. The Code is as follows:

Server:

Create a server main class:

Package COM. home. server; import Java. io. ioexception; import java.net. serversocket; import java.net. socket; import Java. util. arraylist; public class myserver {// defines the set for saving all sockets public static arraylist <socket> socketlist = new arraylist <socket> (); public static void main (string [] ARGs) throws ioexception {serversocket Ss = new serversocket (20000); system. out. println ("server created successfully! "); System. Out. println (" waiting for the connection from the customer terminal... "); While (true) {// This line of code will be blocked, waiting for the user to connect socket = ss. Accept (); system. Out. println (" a client is connected in! "); Socketlist. add (socket); // each time the client connects, start a serverthread to serve the client new thread (New serverthread (socket )). start ();}}}

Server Thread class:

Package COM. home. server; import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstreamreader; import Java. io. outputstream; import java.net. socket; public class serverthread implements runnable {// defines the socketprivate Socket socket processed by the current thread = NULL; // The input stream bufferedreader BR = NULL for the socket processed by the thread; public serverthread (Socket socket) throws ioexception {This. socket = socket; // initialize the input corresponding to the socket Streaming BR = new bufferedreader (New inputstreamreader (socket. getinputstream (), "UTF-8") ;}@ overridepublic void run () {try {string content = NULL; // The while (content = readfromclient () data sent from the client is continuously read from the socket in a loop ())! = NULL) {// traverse each socket in the socketlist and 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 (exception e) {e. printstacktrace () ;}}/*** defines the method for reading client data ** @ return */private string readfromclient () {try {return BR. readline ();} // if an exception is caught, the client corresponding to the socket has closed catch (exception e) {// Delete the socketmyserver. socketlist. remove (socket); E. printstacktrace ();} return NULL ;}}

Client main class (activity ):

Package COM. home. activity; import Java. io. outputstream; import java.net. socket; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. edittext; import COM. home. r; import COM. home. util. clientthread; public class multithreadclient extends activity {private edittext input, show; private button sendbtn; private outputstream OS; private handler; @ overrideprotected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); input = (edittext) findviewbyid (R. id. main_et_input); show = (edittext) findviewbyid (R. id. main_et_show); sendbtn = (button) findviewbyid (R. id. main_btn_send); handler = new handler () {@ overridepublic void handlemessage (Message MSG) {// if the message comes from the subthread if (MSG. what = 0x234) {// append the read content to show in the text box. append ("\ n" + MSG. OBJ. tostring () ;}}; new thread () {public void run () {Socket socket; try {socket = new socket ("192.168.0.101", 20000 ); // The client starts the clientthread thread to constantly read data from the server. New thread (New clientthread (socket, Handler )). start (); OS = socket. getoutputstream ();} catch (exception e) {e. printstacktrace ();}};}. start (); sendbtn. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {try {// write the content entered by the user in the text box to the network OS. write (input. gettext (). tostring () + "\ r \ n "). getbytes (); // clear the input text box data input. settext ("");} catch (exception e) {e. printstacktrace ();}}});}}

Client Thread class:

Package COM. home. util; import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstreamreader; import java.net. socket; import android. OS. handler; import android. OS. message; public class clientthread implements runnable {private handler; // The input stream private bufferedreader BR = NULL for the socket processed by this thread; Public clientthread (Socket socket, Handler handler) throws ioexception {This. handler = Handler; BR = new bufferedreader (New inputstreamreader (socket. getinputstream () ;}@ overridepublic void run () {try {string content = NULL; // read the content of the socket input stream continuously while (content = BR. readline ())! = NULL) {// after reading data from the server, the Message notification program interface displays the data message MSG = new message (); MSG. what = 0x234; MSG. OBJ = content; handler. sendmessage (MSG) ;}} catch (exception e) {e. printstacktrace ();}}}

Activity layout XML:

<Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: layout_width = "match_parent" Android: layout_height = "match_parent" Android: Orientation = "vertical"> <linearlayout Android: layout_width = "match_parent" Android: layout_height = "wrap_content" Android: Orientation = "horizontal"> <edittext Android: Id = "@ + ID/main_et_input" Android: layout_width = "240dp" Android: layout_height = "wrap_content"/> <button Android: Id = "@ + ID/main_btn_send" Android: layout_width = "match_parent" Android: layout_height = "wrap_content" Android: paddingleft = "10dp" Android: text = "send"/> </linearlayout> <edittext Android: Id = "@ + ID/main_et_show" Android: layout_width = "match_parent" Android: layout_height = "match_parent" Android: cursorvisible = "false" Android: editable = "false" Android: gravity = "TOP"/> </linearlayout>

Permission:

<uses-permission android:name="android.permission.INTERNET"/>

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.