Android development to achieve communication between two phones

Source: Internet
Author: User

Welcome reprint, reproduced please indicate the source: http://blog.csdn.net/dmk877/article/details/51685656

Hello, everyone, today again to write a blog, the project has finally finished the recent time to write blog. In the Previous blog We learned the Internet communication in Android , and with the socket to achieve the Android client and server communication, then this article will further improve this function, is to achieve two Android phone-side communication.

If there is falsehood, please criticize, if you have any questions welcome message

Through this blog you will learn the following points of knowledge
The use of ①socket
② how to achieve two mobile phone end of the communication
Tips for streaming in ③java

1, how to achieve two mobile phone end of the communication

Before we begin, we will analyze how to implement this communication, first of all to consider a few questions
① What kind of communication should this real-time communication take?
② how to ensure that the message can reach the party we want to send, that is, a want to communicate with B how to ensure that B received the message is a sent over
③ How to guarantee the real-time message, that is, a send a message B can be received in real time.
To answer these three questions is not difficult, read the Android Development network communication details of this blog children's shoes should be aware that this high-timeliness communication is generally used socket this way of communication, and for the second problem if you want the message to reach our designated party, A and b need to have a unique identity , which we can define by ourselves, the strategy adopted in this article is to define an ID for a and B to uniquely determine it, when a user sends a message, just specify the ID of the user that it wants to send the message to, and it is guaranteed that B receives the message a sent over. Ensure that the real-time nature of the message is solved by using a socket.

2, the realization of two mobile phone-side communication schematic diagram

The process diagram of communication

From what we can clearly see throughout the process the server acts as a relay, CLIENTSOCKET1 first wraps the message into JSON and sends the message to the server, which is then encapsulated to send the messages to ClientSocket2.

3. Realization of two mobile-phone communication clients

Client run ( Note: Here is an entire picture, which is an image ):

The above-mentioned operation results in the communication of two Android machines. Two clients are assigned IDs 0 and 1, respectively. You need to specify the arrival party of the message when you send the message.

3.1 Client Send Message implementation steps

The first step of course is to connect to the server, the way to connect the server is

Clientsocket=new Socket (Ip,port);
that is, set the server's IP and port number, after establishing the connection through while (true) can constantly listen to the server is sent over the message.

The second step is to enter the ID number of the friend you want to send, which will ensure that the message you send will reach the receiver as you expect.

The third step is to send a message when you send a message, you need to be aware that we are encapsulating the message as JSON, and what information is contained in this JSON? There are three kinds of information ① the message sender Id② the content of the message ③ the message arrival party ID.

The code for encapsulating the JSON is as follows

  The BufferedWriter object is obtained from the output stream according to Clientsocket.getoutputstream, Mwriter=new BufferedWriter (New OutputStreamWriter (   Clientsocket.getoutputstream (), "Utf-8"));   。。。。。   Encapsulated as JSON jsonobject JSON = new Jsonobject ();   Json.put ("To", Integer.parseint (friendID));   Json.put ("msg", msgcontent);   Write data to the server via BufferedWriter object Mwriter.write (json.tostring () + "\ n"); Be sure to call flush to write the data in the cache to server Mwriter.flush ();
This JSON contains three messages: ① the content of the message arrival party Id② The message ③ the message sender's ID. After encapsulation, the message is sent to the server via the Write method of Bufferwriter.

3.2 Implementation of client receiving messages

Receiving messages here is using a while loop constantly listening to the server for messages sent over, If a message is sent, the contents of the message are read with a line of BufferedReader, and the main code for the implementation is shown below:

The BufferedReader object is obtained from the Clientsocket.getinputstream to obtain the data from the input stream      mreader=new BufferedReader (New InputStreamReader (Clientsocket.getinputstream (), "Utf-8"));      // The BufferedWriter object is obtained from the Clientsocket.getoutputstream to obtain the data from the output stream      mwriter=new BufferedWriter (New OutputStreamWriter (Clientsocket.getoutputstream (), "Utf-8"));      while (Isreceivingmsgready) {      if (Mreader.ready ()) {        message msg = handler.obtainmessage ();       msg.what=2;        msg.obj=mreader.readline ();        handler.sendmessage (msg);      }       Thread.Sleep ($);      }     mwriter.close ();      mreader.close ();       clientsocket.close (); 

You can see that when the client passes through the while loop when Mreader.ready () is true, it reads a row of the server's return message and then updates the display.
4. Realization of communication Server between two mobile phones

The server-side code I use is MyEclipse, first we take a look at the above-mentioned sending message during the server-side run:

How does the server-side function be implemented? There is no doubt that the first thing to do is to initialize the server and specify the port number, the code is as follows:

ServerSocket = new ServerSocket (socket_port);

Next, when a client connects to the server, it opens a child thread for each client and joins the child thread to the corresponding code in the collection as follows

while (flag) {//has a client connection, the Serversocket.accept () method returns the client socket socket Clientsocket = serversocket.accept ();    Socketthread socketthread = new Socketthread (clientsocket,socketid++);    Socketthread.start ();   Mthreadlist.add (Socketthread); }

a while loop listens for messages sent by the client in the socketthread of the thread that is turned on, and adds the message to the Mthreadlist collection, looping through the messages sent by the client in this child thread .

//loop read messages sent by client     while (flag) {     if (Reader.ready ()) {       string comedata=reader.readline ();       jsonobject MsgJson = new Jsonobject (comedata);       message msg = new Message ();       msg.setto (Msgjson.getint ("to"));       msg.setmsg (MsgJson.getString (" MSG "));       msg.setfrom (Msocketid);        Msg.settime (GetTime (System.currenttimemillis ()))       mmsglist.add (msg);       system.out.println ("User:" +msocketid+ "to the User:" +msg.getto () + "sent the message content is:" +msg.getmsg ());      }     thread.sleep (+);     } 

In fact, in the server for each client connected to the server to open a sub-thread, and in this sub-thread loop to listen to whether the client sent a message, on the above we see the server parsing the message, the message is encapsulated in the bean and added to the collection. The information contained in the message can be seen from the above. Here the server can receive the message sent by the server, the server received the message to do is to send this message to the client, (from the implementation of the schematic diagram can see the role of the server as a relay) then how to achieve this function? Its implementation is not difficult, from the above description we can know that as long as the client sends a message to the server, we will put this message into a collection mmsglist, that is, as long as the server receives the message Mmsglist this collection is not empty, As long as mmsglist this collection is not empty, it means that the server also has messages that are not forwarded and need to be forwarded. How to carry forward it?

First, there are two sets, one is the collection of message mmsglist, and the other is the collection mthreadlist of a child thread Socketthread opened for each client socket. The relationship of these two sets is that each message is definitely sent by a socketthread (client) in Mthreadlist.

When the ID of Socketthread is equal to the to in messsage (that is, the arrival party of the message) Because each client (assuming ClientSocket1) is connected to the server, a Socketthread child thread is opened, and there is a clientSocket1 reference in the child thread. So when equal it means that the message is sent to this clientSocket1. This message is then sent to the client through this clientSocket1 bufferedwriter. Its corresponding code is as follows

while (flag) {      if (mmsglist.size () > 0) {        message from = mmsglist.get (0);        for (Socketthread toThread: Mthreadlist) {        //traversal mthreadlist if to.socketid== From.to explains that this tothread is corresponding to the mmsglist in this article         // Here Tothread's role is to get this message through it bufferedwriter,mmsglist.get (0) and then through          //bufferedwriter sends this message to the specified party         if (Tothread.msocketid = = From.getto ()) {         //Writer is a writer in Socketthread, This ensures that the message arrives          //our designated party after the call to Writer.flush           bufferedwriter writer = tothread.writer;          jsonobject json = new Jsonobject ();   &Nbsp;      json.put ("from", From.getfrom ());          json.put ("msg", from.getmsg ());          json.put ("Time", From.gettime ());          writer.write (json.toString () + "\ n ");          writer.flush ();          SYSTEM.OUT.PRINTLN ("forwarded message succeeded");         break;         }       }        mmsglist.remove (0);      }       thread.sleep ($);      }

This message parsing is encapsulated into JSON and sent to the specified client, completing the communication of two Android machines. In fact, individuals feel that the knowledge of these principles or need to study hard, understand, and its realization of the idea of our future programming is also very useful.

On the realization of two mobile phone-side communication is here, perhaps we see that the communication software is not used in the way this article, but the original rational things will not change, this blog is from the most primitive place to understand the mobile phone communication of some simple principles.

If there is falsehood, welcome criticism, if you have any questions welcome message.

If this blog is helpful to you click on the top left-hand corner, follow it, lock the station to see more wonderful content 0.0

Note here that the source code contains two parts, part of the service side, the other part is the client, the server is the MyEclipse program, the client is our Android program.

Source Poke here


Welcome reprint, reproduced please indicate the source: http://blog.csdn.net/dmk877/article/details/51685656



Android development to achieve communication between two phones

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.