Android TCP and UDP summary (RPM)

Source: Internet
Author: User

Previously written about TCP and UDP data transmission code, such as the use of TCP transmission of audio and video packets, peer-to-hole use of UDP and so on. After writing it, I dropped it immediately, without summing it up. Recently prepared to find a job, and then to review.

1, or say something first

Temporarily put their own positioning is very clear, is the development of Android application layer, so about the implementation of TCP/UDP details, and temporarily do not want to go into the drill. But the heart clear this must go to see, have time to recommend everyone to see "TCP/IP detailed", or online there are a lot of Daniel's summary.

2. TCP

Do not know why, this summary do not want to write too thin, do not paste code to write the fine and do not know what to summarize, good entanglements, may be a limited understanding of it, the company if there is a structure is good. Do not say, or peacefully to write a summary of it. TCP This may be we use more or I use more, the main job is to carry out a large amount of data transmission and heartbeat maintenance (think about the interview last year did not know what is the heartbeat, Khan ...) )。 For the heartbeat to keep, is a simple small heartbeat package; the transmission of large amounts of data, this also can not summarize what things, code, that is, some details to say.

Client: This is the most we pay attention to, but also as a mobile app is the main concern, because we are clienta, create a client socket
New Socket (IP, prot);

We can create a socket in the way above and throw ioexception if it fails. The IP and port in the parameter are the IP and port number of the destination server. If you want the local IP and port can be obtained through this socket. Of course, there are a number of construction methods for creating sockets, such as new sockets, which you can refer to if necessary.

B. Sending and receiving data

The next thing we do when we get the socket object is to get the input and output streams from this socket, so that we can send and receive the data:

InputStream is = Msocket.getinputstream (), outputstream out = Msocket.getoutputstream ();

With the output stream, we can use Is.read (Receivebuffer) and Out.write (data) to send and receive the information. Here are two simple examples:

Receive data:
@Overridepublic void execute () {try {int count = Is.read (Receivebuffer); if (count = =-1) {notifyerror ();} byte[] data = GetPacket (Receivebuffer, Count, is); mreceiverqueue.put (data);} catch (Interruptedexception e) {e.printstacktrace (); Notifyerror ();} catch (IOException e) {e.printstacktrace (); Notifyerror ();}}

If our packet protocol format is as follows:

At this time, if we are doing a lot of data transfer, we may not have a complete packet when we read from InputStream. This time we need to make the following judgment: A, read the length of the data to reach the Baotou size, if there is no Baotou long, continue to read until the size of the Baotou; B, the length of the field from the Baotou, the loop read, until the length of the field to read the length of the date; Repeat the steps above.

Send data:
@Overridepublic void execute () {try {byte[] data = Msenderqueue.take (); out.write (data);} catch (Interruptedexception e) { E.printstacktrace (); Notifyerror ();} catch (IOException e) {e.printstacktrace (); Notifyerror ();}}

Msenderqueue, like Mreceiverqueue, are blocking queues. When sending, we take out the data to be sent from the queue and write it through the output stream. This place is a little simpler than sending it. You may have noticed that my send and receive all use blocking queues, which is due to the fact that there is a buffer for large amounts of data, and if there is no buffering, it can cause code blocking. In addition, when our blocking queue is full, we can discard some data manually, this is the specific application.

Server: This can be easily understood, can be implemented in Java, but also C + + and other implementation

First, we create a ServerSocket object and specify a port number to wait for the client's connection through the accept () method of the object, which is blocked, and when a client connects, we get the connected socket. After you get this socket, the operation is the same as the client, and finally look at the key code:

try {serversocket serversocket = new ServerSocket (9559), while (true) {Socket socket = serversocket.accept ();//New Service Socketthread (socket). Start ();}} catch (Exception e) {e.printstacktrace ();}

Because the server cannot connect to only one client, the above code is written in a dead loop. After you get the socket, a new thread is started to handle the socket.

Finally, it's important to note that if you close them after you get InputStream and outputstream from the socket, the socket will also close (not verified).

3. UDP

This thing is used very little, that is, when the peer test was used. The problem that can be thought of is the size of the data, such as sending the data how much our data is defined as appropriate. But in the end there is no actual project validation, and this is not a good answer. Put a piece of code on it first:

public class Udpserver extends Basethread {/** send queue size */public static final int sendqueuesize = 10;/** Receive Queue size */public STA Tic Final int receivequeuesize = 10;/** TCP receive cache size */public static final int receiverbuffersize = 1024;/** UDP receive cache size */PUBL IC static final int receiverpacketsize = 1024x768 * 64;private int count = 0;private datagrampacket receivepacket;private Data Gramsocket Msocket; @Overridepublic Boolean prepare () {receivepacket = new Datagrampacket (new Byte[receiverpacketsize], Receiverpacketsize); try {msocket = new Datagramsocket (9559);} catch (SocketException e) {System.out.println ( String.Format ("UDP Connect init Error:%s", E.getmessage ())); return false;} return true;} @Overridepublic void execute () {try {msocket.receive (receivepacket); byte[] data = Receivepacket.getdata (); int length = Receivepacket.getlength (); int offset = Receivepacket.getoffset (); System.out.print (++count+ String.Format ("length:%d|%d, offset:%d, data:%s \ n", length, data.length, offset, new String ( Data, "GBK")));System.out.println (data[1024]);} catch (SocketException e) {System.out.println (String.Format ("UDP Connect init Error:%s", E.getmessage ()));} catch ( IOException e) {System.out.println (String.Format ("UDP Connect init Error:%s", E.getmessage ()));}}

byte[] data = Receivepacket.getdata (); This place gets the data is the buffer size, their address is kind, this people can try to know. As to how much data there is, we need to pass receivepacket.getlength (); Get it.

Android TCP and UDP summary (RPM)

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.