Android enables instant messaging based on TCP and UDP protocols, including Android and server-side

Source: Internet
Author: User
Tags sendmsg


These days to learn the next in the Android to achieve instant communication method, at the beginning, naturally from the basic network protocol began to try, so that can maximize the private custom of their own applications, but also learn more knowledge, the benefits of a lot, then simply introduce the next two kinds of protocol differences

TCP protocol: provides reliable transmission of data in an IP environment , which provides services including data flow transmission, reliability, effective flow control, full duplex operation and multiplexing. Send through connection-oriented, end-to-end, and reliable packets . As for the two people on the cliff communication, he must first set up the bridge, confirm that the bridge is not a problem in the case, before the letter handed over, in the future, every time we communicate, we confirm that the next bridge is no problem, and then through the bridge to communicate back and forth.

UDP protocol: do not provide reliability, flow control or error recovery for IP, do not have to establish a connection with the other party before the official communication, regardless of the status of the other party directly sent. This is the Flying Pigeon biography ~

Although UDP is less reliable than the TCP protocol, communication efficiency is higher than TCP. In the case of extremely poor speed, the UDP protocol is preferred, TCP is very convenient to use when the network speed is good.

Using TCP in Java can be done by java.net.Socket; this class

<span style= "Font-family:microsoft yahei;font-size:18px;" > Establishing a Connection </span>
<span style= "Font-family:microsoft yahei;font-size:18px;" >//instantiate a Socket object socket = new socket ();//Connect to the corresponding IP and port, first build the bridge well Socket.connect (new Inetsocketaddress (IP, Port), 3000) ;</span>
<span style= "Font-family:microsoft yahei;font-size:18px;" > Send Information </span>
</pre><pre name= "code" class= "java" ><span style= "Font-family:microsoft yahei;font-size:18px;" >inputstream ois = Socket.getinputstream ();D atainputstream dis = new DataInputStream (new Bufferedinputstream (OIS)) ///Read the information sent by the server, if no information will block the thread msg =  Dis.readutf ();</span>
<span style= "Font-family:microsoft yahei;font-size:18px;" > Send Information </span>
<span style= "Font-family:microsoft yahei;font-size:18px;" >//get output stream DataOutputStream dos = new DataOutputStream (New Bufferedoutputstream (Socket.getoutputstream ()));// Send Data Dos.writeutf (msg);</span>

Next, the source code, for three thread subclasses, respectively, corresponding to the above three

<span style= "Font-family:microsoft yahei;font-size:18px;" >public class Socketthread extends Thread{private Socket socket;private Client client;private String ip;private int por T;private boolean isstart=false;private messagelistener mmessagelistener;/** * * Use the TCP protocol, connect to access * @param IP target Machine IP * @para M Port * @param mmessagelistener receives server-side data, it will callback the * public void Message (String msg) method within the interface */public socketthread (string IP , int port,messagelistener mmessagelistener) {this.ip = Ip;this.port = Port;this.mmessagelistener = MMessageListener;} public void Run () {try {//Instantiate a Socket object socket = new socket ();//Connect to the corresponding IP, port, first build the bridge Socket.connect (new Inetsocketaddress (IP, Port), (socket.isconnected ()) {System.out.println ("Connected."); Client = new Client (socket,mmessagelistener);//Open the corresponding input/output stream listener Client.start (); isstart=true;}} catch (IOException e) {e.printstacktrace (); isstart=false;}} Directly through the client get read thread public clientinputthread Getclientinputthread () {return client.getin ();} Get a write thread directly from the clientPublic Clientoutputthread Getclientoutputthread () {return client.getout ();} Returns the socket state public boolean Isstart () {return isstart;} Stop reading and writing messages directly through the client public void Setisstart (Boolean isstart) {This.isstart = Isstart;client.getin (). Setstart (Isstart); Client.getout (). Setstart (Isstart);} Send Message public void sendmsg (String msg) {client.getout (). sendmsg (msg);} public class Client {private Clientinputthread in;private clientoutputthread out;public Client (socket socket, MessageListener mmessagelistener) {//Use this listener input stream to receive information in = new clientinputthread (socket); In.setmessagelistener ( Mmessagelistener), or//the thread that listens to the output stream later sends the message out = new Clientoutputthread (socket);} public void Start () {In.setstart (true); Out.setstart (true); In.start (); Out.start ();} Get read message thread public clientinputthread Getin () {return in;} Get write message thread public Clientoutputthread getout () {return out;}}} </span>

<span style= "Font-family:microsoft yahei;font-size:18px;" >public class Clientinputthread extends Thread {private Socket socket;private String msg;private Boolean Isstart = True ;p rivate inputstream ois;private datainputstream dis;private messagelistener messagelistener;//Message Listener Interface Object Public Clientinputthread (socket socket) {This.socket = socket;try {ois = Socket.getinputstream ();d is = new DataInputStream (New B Ufferedinputstream (OIS));} catch (IOException e) {e.printstacktrace ();}} /** * Provides external message listener method * * @param messagelistener * Message Listener Interface object */public void Setmessagelistener (MessageListener mess Agelistener) {this.messagelistener = MessageListener;} public void Setstart (Boolean isstart) {this.isstart = Isstart;} @Overridepublic void Run () {try {while (Isstart) {//reads information, if no information will block the thread msg = DIS.READUTF ();//Each message is received, the method message of the interface is called ( String msg) LOG.V ("Received message", MSG); Messagelistener.message (msg);} Ois.close (); if (socket! = NULL) Socket.close ();} catch (IOException e) {e.printstacktrace ();}} BufferEdreader reader=null;public String getinputstreamstring () {/* * to convert the InputStream to String we use the * Buffered Reader.readline () method. We iterate until the BufferedReader * return null which means there ' s no more data to read. Each line would * appended to a StringBuilder and returned as String. */if (OIS! = null) {reader = new BufferedReader (new InputStreamReader (OIS));} StringBuilder sb = new StringBuilder (); String line = null;try {when (line = Reader.readline ())! = null) {Sb.append (line + "\ n")}} catch (IOException e) {E.pri Ntstacktrace ();} return sb.tostring ();}} </span>

<span style= "Font-family:microsoft yahei;font-size:18px;" >public class Clientoutputthread extends Thread {private Socket socket;private DataOutputStream Dos;private Boolean is Start = true;private String msg;public clientoutputthread (socket socket) {This.socket = socket;try {dos = new dataoutputst Ream (New Bufferedoutputstream (Socket.getoutputstream ())); catch (IOException e) {e.printstacktrace ();}} public void Setstart (Boolean isstart) {this.isstart = Isstart;} This handles the same as the server, public void sendmsg (String msg) {this.msg = msg;synchronized (this) {Notifyall ()}} @Overridepublic void Run () {try {while (Isstart) {if (msg! = null) {DOS.WRITEUTF (msg);d Os.flush (); Msg=null;synchronized ( This) {wait ();//After the message is sent, the thread enters the wait state}}}dos.close ();//After the loop ends, the output stream is closed and socketif (socket! = NULL) Socket.close ();} catch (Interruptedexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ()}}} </span>
<span style= "Font-family:microsoft yahei;font-size:18px;" >//defines the interface that handles the message when the message is received public interface MessageListener {public void message (String msg); </span>

The main interface, it feels ugly.

<span style= "Font-family:microsoft yahei;font-size:18px;" ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools: context= "Com.example.chatclient.MainActivity" > <scrollview android:id= "@+id/svmessage" Android:lay Out_width= "Fill_parent" android:layout_height= "100DP" > <textview android:id= "@+id/tvmessag E "android:layout_width=" Wrap_content "android:layout_height=" Wrap_content "android:text= "Message content: \ n"/> </ScrollView> <edittext android:id= "@+id/etmessage" android:layout_width= "100DP "android:layout_height=" wrap_content "android:layout_below=" @+id/svmessage "/> <textview Android:id= "@+id/tvsend" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" a ndroid:layout_below= "@+id/svmessage" android:layout_marginleft= "10DP" android:layout_torightof= "@+id/etMessa GE "android:text=" send Message "android:textsize=" 25sp "/>" </RelativeLayout></span>

Mainactivity Code

<span style= "Font-family:microsoft yahei;font-size:18px;" >public class Mainactivity extends Activity {EditText etmessage; TextView Tvsend, Tvmessage; Socketthread client; MyHandler MyHandler; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate) ; Setcontentview (r.layout.activity_main); setup ();} public void Setup () {etmessage = (EditText) Findviewbyid (r.id.etmessage); tvsend = (TextView) Findviewbyid (r.id.tvsend); Tvmessage = (TextView) Findviewbyid (r.id.tvmessage); Tvsend.setonclicklistener (onClick); MyHandler = new MyHandler (); /Initialize client = new Socketthread ("10.21.56.226", 8888,new MessageListener () {//) Call this method after receiving the message @overridepublic void message ( String msg) {//TODO auto-generated method stub//tvmessage.append (msg); Bundle bundle = new bundle (); Bundle.putstring ("Input", msg); Message Ismessage = new Message (); Ismessage.setdata (bundle);//Use Handler to forward myhandler.sendmessage (Ismessage);}}); /formally Start thread Client.start ();} Onclicklistener OnClick = new Onclicklistener ({public void OnClick (Android.view.View v) {String message = Etmessage.gettext (). toString (); LOG.V ("Send Message", message), if (Client.isstart ()) {client.sendmsg (message);};}; Private class MyHandler extends Handler {@Overridepublic void Handlemessage (Message msg) {//TODO auto-generated Method St UBLOG.V ("Process received message", ""); Tvmessage.append (Msg.getdata (). getString ("input"));}} </span>


server-side code, mainly using ServerSocket to listen to a port, to link with the client and send and receive information

<span style= "Font-family:microsoft yahei;font-size:18px;"    >public class Chatserver {Boolean started = false;    ServerSocket SS = null;    list<client> clients = new arraylist<client> ();    public static void Main (string[] args) {new Chatserver (). Start ();    } public void Start () {try {//serversocket listens on 8888 port SS = new ServerSocket (8888); started = true;}    catch (Bindexception e) {System.out.println ("start ...");    System.out.println ("problematic");    E.printstacktrace (); System.exit (0);} catch (IOException e) {e.printstacktrace ();} try {while (started) {Socket s = ss.accept (); Client C = new client (s); SYSTEM.OUT.PRINTLN ("A client connected!");    New Thread (c). Start (); Clients.add (c);//Dis.close ();    }} catch (IOException e) {e.printstacktrace ();} finally {try {ss.close ();    } catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace (); }}} class Client implements Runnable {private Socket s;private DataInputStreamdis = null;private DataOutputStream dos = null;private Boolean bconnected = False;public Client (Socket s) {this.s = s;    try {dis = new DataInputStream (S.getinputstream ());d OS = new DataOutputStream (S.getoutputstream ()); bconnected = true;    } catch (IOException e) {e.printstacktrace ();    }}public void Send (String str) {try {dos.writeutf (str); } catch (IOException e) {clients.remove (this);    System.out.println ("Close a Connection");//E.printstacktrace ();    }}public void Run () {try {while (bconnected) {String str = DIS.READUTF ();    System.out.println (str); for (int i = 0; i < clients.size (); i++) {Client c = clients.get (i); c.send (str);//System.out.println ("A String send!    ");     }/* * for (iterator<client> it = Clients.iterator (); * It.hasnext ();     {Client c = it.next (); c.send (str);}     */* * iterator<client> it = clients.iterator ();     * while (It.hasnext ()) {Client c = it.next (); c.send (str); *} */}} catch (Eofexception e) {System.out.println ("Client closed!");    } catch (IOException e) {e.printstacktrace ();    } finally {try {System.out.println ("Close all!");    if (dis! = null) dis.close ();    if (dos = null) dos.close ();    if (s! = null) {s.close ();//s = null;    }} catch (IOException E1) {e1.printstacktrace ();} }}}}</span>
Next run the server code, and then run the phone side on it, more than one phone can send each other information.
I'll write the UDP later.





Android enables instant messaging based on TCP and UDP protocols, including Android and server-side

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.