How to implement message push using socket communication in Android _android

Source: Internet
Author: User
Tags flush gettext message queue readline sendmsg static class stringbuffer

Principle
recently used a socket to write a message to push the demo, here and share with you.

Mainly realized: a mobile phone to another cell phone to send messages, the two mobile phones can be free to send text messages to communicate, similar to our commonly used QQ.

Effect Chart:

Principle: Mobile phone through the socket to send messages to the server, every time the server received a message, will put this message into a messagelist inside, the server will constantly detect whether messagelist contains messages, If some words will be based on the messagelist inside the item data, pushed to the corresponding other end of the phone.

Here's a simple diagram to illustrate this principle:

Demo: Mobile phone client client1 send message MSG1 to the mobile phone client Client2,client2 received a message after the reply MSG2 to Client1

1. Mobile Client client1 send a "MSG1" text message to the server;

2. The server received from the CLIENT1 "MSG1" message, add it into the messagelist inside;

3. The server detects that messagelist contains messages (when the server is opened on a new detection messagelist thread, the thread has a dead loop, used to constantly detect whether the messagelist contains messages);

4. The server reads the message data, such as reading the message "MSG1" from Client1 to Client2, then the server pushes "MSG1" to Client2;

5.client2 detects the server push message, makes the corresponding operation (such as: vibration, ringtones, display messages, etc.);

6.client2 receives the "MSG1" message from the server push, Client2 also replies a text message "MSG2" to CLIENT1, which sends a message to CLIENT1 as well.

7. Finally, Client2 can display the message "MSG1" sent from CLIENT1, and client1 can display the reply message "Client2" from MSG2.

Implementation process
based on the schematic diagram of message push, our implementation process is mainly divided into server and client side, server-side with Java programming, and client side with Android programming.

So here are two engineering socketserver and Socketclient, respectively.

Let's take a look at the Socketmessage.java class:

public class Socketmessage {public 
 
  int To;//socketid, who is sent to 
  the public int From;//socketid, who is sent over to the public 
  String msg;//message content public 
  string time;//receive time public 
  Socketthread Thread;//socketthread here is an introduction 
} 

This class is a message class, which is used to indicate who sent the message, what the message was, what time it was received, only a few attributes, simpler.

And the Myserver.java class is relatively more code:

Package com.jimstin.server; 
Import Java.io.BufferedReader; 
Import Java.io.BufferedWriter; 
Import Java.io.InputStreamReader; 
Import Java.io.OutputStreamWriter; 
Import Java.net.ServerSocket; 
Import Java.net.Socket; 
Import Java.text.SimpleDateFormat; 
Import java.util.ArrayList; 
 
Import Java.util.Date; 
 
 
Import Org.json.JSONObject; 
 
Import Com.jimstin.msg.SocketMessage; 
  public class MyServer {private Boolean isstartserver; 
  Private ServerSocket Mserver; /** * Message Queuing, which is used to save socketserver receive messages from the client side (mobile)/private arraylist<socketmessage> mmsglist = new arraylist& Lt 
  Socketmessage> (); /** * thread queue, used to receive messages. Each client has a thread, and each thread receives only messages sent to itself/private arraylist<socketthread> mthreadlist = new Arraylist<socketthread&gt 
   
  ;(); 
      /** * Open Socketserver * * private void Startsocket () {try {isstartserver = true; int prot = 2000;//Port can be set itself, but to be consistent with the port on the client side mserver = new ServerSocket (prot);//Create a SERVERSOCKet System.out.println ("Boot server, Port:" +prot); 
      Socket socket = NULL; int socketid = 0;//android (socketclient) client's unique flag, each Socketid represents an Android client//Open Send Message Thread startsendmessagethread ( 
      ); Using a loop to detect whether a new client joins the while (Isstartserver) {//accept () method is a blocking method, after calling the method,//the thread blocks until a new client is joined, and the code 
        will continue to go down the socket = mserver.accept (); 
        When a new client is joined, a new Socketthread thread object is created socketthread threads = new Socketthread (socket, socketid++); 
        Thread.Start (); 
      Add this thread to the thread queue Mthreadlist.add (thread); 
    } catch (Exception e) {e.printstacktrace (); /** * Opens the push message thread, if there is a socketmessage in the mmsglist, pushes the message to the Android client/public void Startsendmessagethread 
        () {new Thread () {@Override public void run () {super.run (); 
        try {/* if isstartserver=true, then the Socketserver is started, a loop is used to detect if there is a message in the message queue, and if so, push the message to the appropriate client * *  while (isstartserver) {//Determine whether the length in Message Queuing is greater than 0, or greater than 0 indicates that Message Queuing is not empty if (mmsglist.size () > 0) { 
              Reads the first message in a message queue socketmessage from = mmsglist.get (0); for (Socketthread to:mthreadlist) {if (To.socketid = = from.to) {BufferedWriter Write 
                  R = To.writer; 
                  Jsonobject json = new Jsonobject (); 
                  Json.put ("from", From.from); 
                  Json.put ("msg", from.msg); 
                  Json.put ("Time", from.time); 
                  Writer writes into the string data in JSON and remembers the line break at the end: "\ n", otherwise unrecognized on the client side//Because the Bufferedreader.readline () method reads a row based on a newline character 
                  Writer.write (json.tostring () + "\ n"); 
                  Call the Flush () method, refresh the stream buffer, push the message to the mobile phone end writer.flush (); 
                  SYSTEM.OUT.PRINTLN ("Push message succeeded:" +from.msg+ ">> to Socketid:" +from.to); 
                Break After each push a message is sent to the message teamColumn to remove the message mmsglist.remove (0); 
          } thread.sleep (200); 
        } catch (Exception e) {e.printstacktrace (); 
  }}.start (); /** * Defines a Socketthread class for receiving messages * */public class Socketthread extends Thread {public I 
    NT Socketid; The public Socket Socket;//socket is used to get the input stream, the output stream public bufferedwriter Writer;//bufferedwriter for the push message public Bufferedrea 
      Der Reader;//bufferedreader is used to receive message public socketthread (socket socket, int count) {Socketid = count; 
      This.socket = socket; 
    System.out.println ("Add a client, Socketid:" +socketid); 
 
      @Override public void Run () {super.run (); try {//initialize BufferedReader reader = new BufferedReader (New InputStreamReader (Socket.getinputstream (), UT 
        F-8 ")); Initialize BufferedWriter writer = new BufferedWriter (new OutputStreamWriter (Socket.getoutputstream), "Utf-8")); 
          If isstartserver=true, then Socketserver has started,//now requires a loop to continuously receive messages from the client and do other processing while (Isstartserver) { First determine if reader is ready for if (Reader.ready ()) {/* read a line of strings, read from the client Reader.readline () Method is a blocking method, starting with this method, the thread will remain blocked until a new message is received, and the code will go down */String data = Reader.readlin 
            E (); 
            Tells data as the content of the JSON object, creating a JSON object jsonobject JSON = new Jsonobject (data); 
            Creates a Socketmessage object that receives data from JSON socketmessage msg = new Socketmessage (); 
            Msg.to = Json.getint ("to"); 
            Msg.msg = json.getstring ("msg"); 
            Msg.from = Socketid; 
            Msg.time = GetTime (System.currenttimemillis ()); 
            After receiving a message, add the message to Message Queuing mmsglist mmsglist.add (msg); 
          System.out.println ("received a message:" +json.getstring ("msg") + ">>>> to Socketid:" +json.getint ("to")); }//Sleep 100ms, per100ms detect whether a message was received thread.sleep (100); 
      } catch (Exception e) {e.printstacktrace (); /** * Gets the time string in the specified format, through the millisecond conversion date * @param milltime/private String getTime (Long Mill 
    Time) {Date d = new Date (milltime); 
    SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); 
  Return Sdf.format (d); 
    public static void Main (string[] args) {MyServer server = new MyServer (); 
  Server.startsocket (); 
 } 
 
}

2.SocketClient Engineering

The project is an Android project, with only one Mainactivity.java and Activity_main.xml file,

First look at the Activity_main.xml layout file:

<linearlayout 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 "Tools:context" =". 
    Mainactivity "android:orientation=" vertical "> <linearlayout android:layout_width=" match_parent " android:layout_height= "wrap_content" android:orientation= "horizontal" > <edittext android:id= "@+i" 
      D/ip_edt "android:layout_width=" 0DP "android:layout_height=" Wrap_content "android:layout_weight=" 1 " 
      Android:hint= "IP" android:text= "172.16.1.200"/> <edittext android:id= "@+id/port_edt" Android:layout_width= "0DP" android:layout_height= "Wrap_content" android:layout_weight= "1" android:h Int= "Port" android:text= "/>" </LinearLayout> <button android:id= "@+id/start_btn" a Ndroid:layout_width= "Match_parent" android:layout_height= "Wrap_content" android:text= "Start"/> <edittext android:id= "@+id/socket_id_edt" 
   
 
   
  Android:layout_width= "Match_parent" android:layout_height= "wrap_content" android:hint= "SocketID"/> <edittext android:id= "@+id/msg_edt" android:layout_width= match_parent "android:layout_height=" Wra  
    P_content "android:minlines=" 5 "android:hint=" Content "android:gravity=" top "/> <button Android:id= "@+id/send_btn" android:layout_width= "match_parent" android:layout_height= "Wrap_content" Androi d:text= "Send"/> <textview android:id= "@+id/console_txt" android:layout_width= "Match_parent" Andro id:layout_height= "0DP" android:layout_weight= "1"/> <button android:id= "@+id/clear_btn" Android: Layout_width= "Match_parent" android:layout_height= "wrap_content" android:text= "clear"/> </LinearLayout&gt 

 ;

Effect Chart:

Mainactivity.java class:

Package com.jimstin.socketclient; 
Import Java.io.BufferedReader; 
Import Java.io.BufferedWriter; 
Import java.io.IOException; 
Import Java.io.InputStreamReader; 
Import Java.io.OutputStreamWriter; 
Import Java.net.Socket; 
Import java.net.UnknownHostException; 
Import Java.text.SimpleDateFormat; 
 
Import Java.util.Date; 
 
Import Org.json.JSONObject; 
Import com.tencent.stat.MtaSDkException; 
Import Com.tencent.stat.StatConfig; 
 
Import Com.tencent.stat.StatService; Import Android. 
R.integer; 
Import Android.os.AsyncTask; 
Import Android.os.Bundle; 
Import Android.os.Handler; 
Import Android.os.Message; 
Import Android.util.Log; 
Import Android.view.View; 
Import Android.view.View.OnClickListener; 
Import Android.widget.EditText; 
Import Android.widget.TextView; 
Import Android.widget.Toast; 
 
Import android.app.Activity; public class Mainactivity extends activity implements Onclicklistener {private EditText Mipedt, Mportedt, Msocketide 
  DT, Mmessageedt; private static TExtview Mconsoletxt; 
  private static StringBuffer mconsolestr = new StringBuffer (); 
  Private Socket Msocket; 
   
  Private Boolean isstartrecievemsg; 
  Private Sockethandler Mhandler; 
   
  Protected BufferedReader Mreader;//bufferedwriter for push messages protected BufferedWriter Mwriter;//bufferedreader used to receive messages 
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
    Setcontentview (R.layout.activity_main); 
  Initview (); 
    private void Initview () {Mipedt = (edittext) Findviewbyid (R.id.ip_edt); 
    Mportedt = (edittext) Findviewbyid (R.id.port_edt); 
    Msocketidedt = (edittext) Findviewbyid (R.id.socket_id_edt); 
    Mmessageedt = (edittext) Findviewbyid (R.id.msg_edt); 
    Mconsoletxt = (TextView) Findviewbyid (r.id.console_txt); 
    Findviewbyid (R.ID.START_BTN). Setonclicklistener (this); 
    Findviewbyid (R.ID.SEND_BTN). Setonclicklistener (this); 
 Findviewbyid (R.ID.CLEAR_BTN). Setonclicklistener (this);   Mhandler = new Sockethandler ();  /** * Initialize socket/private void Initsocket () {//Create a new thread to initialize the socket and detect whether there is a new message thread thread = new Thread (new Runnable () {@Override public void run () {String IP = mipedt.gettext (). t 
          Ostring ();//ip int port = integer.parseint (Mportedt.gettext (). toString ());//socket try { 
          Isstartrecievemsg = true; 
          Msocket = new Socket (IP, port); 
          Mreader = new BufferedReader (New InputStreamReader (Msocket.getinputstream (), "Utf-8")); 
          Mwriter = new BufferedWriter (New OutputStreamWriter (Msocket.getoutputstream (), "Utf-8")); while (isstartrecievemsg) {if (Mreader.ready ()) {*/* reads a line of strings, and the contents are read from the client READER.R  The Eadline () method is a blocking method, starting with this method, the thread will remain blocked until a new message is received, and the code will go down/String data = 
              Mreader.readline (); Handler send message, in Handlemessage ()method to receive Mhandler.obtainmessage (0, data). Sendtotarget (); 
          } thread.sleep (200); 
          } mwriter.close (); 
          Mreader.close (); 
        Msocket.close (); 
        catch (Exception e) {e.printstacktrace (); 
    }  
      } 
    }); 
  Thread.Start (); 
      @Override public void OnClick (View v) {switch (V.getid ()) {case r.id.send_btn:send (); 
    Break 
      Case R.id.clear_btn:mconsolestr.delete (0, Mconsolestr.length ()); 
      Mconsoletxt.settext (Mconsolestr.tostring ()); 
    Break 
      Case R.id.start_btn:if (!isstartrecievemsg) {initsocket (); 
    } break; 
    Default:break; }/** * Send/private void Send () {new asynctask<string, Integer, string> () {@O 
        Verride protected string Doinbackground (String ... params) {sendmsg (); 
      return null; }}.execute (); /** * Send message */protected void sendmsg () {try {String Socketid = Msocketidedt.gettext (). Tostri 
      Ng (). Trim (); 
      String msg = Mmessageedt.gettext (). toString (). Trim (); 
      Jsonobject json = new Jsonobject (); 
      Json.put ("to", Socketid); 
      Json.put ("msg", MSG); 
      Mwriter.write (json.tostring () + "\ n"); 
      Mwriter.flush (); 
      Mconsolestr.append ("Me:" +msg+ "" +gettime (System.currenttimemillis ()) + "\ n"); 
    Mconsoletxt.settext (MCONSOLESTR); 
    catch (Exception e) {e.printstacktrace (); } static class Sockethandler extends Handler {@Override public void Handlemessage (msg) 
      {//TODO auto-generated Method Stub super.handlemessage (msg); Switch (msg.what) {case 0:try {//Send message from handler create JSON object Jsonobject JSON = new J 
          Sonobject ((String) msg.obj); Mconsolestr.append (Json.getstring ("from") + ":" +json.getstring ("msg") + " "+gettime (System.currenttimemillis ()) +" \ n "); 
        Displays the JSON data in the TextView mconsoletxt.settext (MCONSOLESTR); 
        catch (Exception e) {e.printstacktrace (); 
 
      } break; 
      Default:break; 
    @Override public void onbackpressed () {super.onbackpressed ()}}} 
  Isstartrecievemsg = false; 
    private static String GetTime (long milltime) {Date d = new Date (milltime); 
    SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); 
  Return Sdf.format (d); 

 } 
   
}

The comments in the above code are more detailed and will not be added.

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.