An example of UDP communication model for Android network programming _android

Source: Internet
Author: User

What is Android UDP?

UDP is the abbreviation of User Datagram protocol, the Chinese name is the Subscriber packet protocol, is a connectionless transport layer protocol in the OSI Reference Model, and it provides a simple and unreliable information delivery service for transaction-oriented. It is the official specification of the IETF RFC 768 that is UDP. It is used in the network as a TCP protocol for processing packets. In the OSI model, the layer fourth-transport layer is at the upper level of the IP protocol. UDP has the disadvantage of not providing datagram grouping, assembling and sorting packets, that is, when a message is sent, it is not possible to know whether it has arrived safely or completely. UDP is used to support network applications that need to transfer data between computers. The UDP protocol is needed for the network applications of many client/server modes including the network video conferencing system. The UDP protocol has been in use for many years since its inception, although its initial brilliance has been overshadowed by similar protocols, but even today, UDP is a very practical and feasible network transport protocol.

As with the well-known TCP (Control Protocol) protocol, the UDP protocol is directly at the top of the IP (Internet Protocol) protocol. According to the OSI (Open Systems Interconnection) Reference model, both UDP and TCP belong to the Transport layer protocol.

The main function of UDP protocol is to compress the network data traffic into the form of datagram. A typical datagram is a transmission unit of binary data. The first 8 bytes of each datagram are used to contain header information, and the remaining bytes are used to contain the specific transmitted data.

The use of TCP and UDP in Android is exactly the same as in Java.

Service side:

Copy Code code as follows:

Package Com.cheerchip.core;

Import java.io.IOException;
Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;
Import java.net.SocketException;

Import Android.util.Log;

public class Udpserver implements Runnable {

private static final int PORT = 6000;

Private byte[] msg = new byte[1024];

Private Boolean life = true;

Public Udpserver () {
}

/**
* @return The Life
*/
public Boolean islife () {
return life;
}

/**
* @param life
* The life to set
*/
public void Setlife (Boolean life) {
This.life = life;
}

@Override
public void Run () {
Datagramsocket dsocket = null;
Datagrampacket dpacket = new Datagrampacket (msg, msg.length);
try {
Dsocket = new Datagramsocket (PORT);
while (Life) {
try {
Dsocket.receive (Dpacket);
LOG.I ("Msg Sever received", New String (Dpacket.getdata ()));
catch (IOException e) {
E.printstacktrace ();
}
}
catch (SocketException e) {
E.printstacktrace ();
}
}
}

Client:

Copy Code code as follows:

Package Com.cheerchip.core;

Import java.io.IOException;
Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;
Import java.net.InetAddress;
Import java.net.SocketException;
Import java.net.UnknownHostException;

public class UdpClient {

private static final int server_port = 6000;

Private Datagramsocket dsocket = null;

Private String msg;

/**
* @param msg
*/
Public UdpClient (String msg) {
Super ();
this.msg = msg;
}

/**
* Send information to server
*/
Public String Send () {
StringBuilder sb = new StringBuilder ();
InetAddress local = null;
try {
Local = Inetaddress.getbyname ("localhost"); Native test
Sb.append ("Server found, Connection ..."). Append ("n");
catch (Unknownhostexception e) {
Sb.append ("Server not Found."). Append ("n");
E.printstacktrace ();
}
try {
Dsocket = new Datagramsocket (); Note that you must set permissions in the configuration file first, otherwise you will throw the exception of insufficient permissions
Sb.append ("Connecting server ..."). Append ("n");
catch (SocketException e) {
E.printstacktrace ();
Sb.append ("Server connection failed."). Append ("n");
}
int msg_len = MSG = null? 0:msg.length ();
Datagrampacket dpacket = new Datagrampacket (Msg.getbytes (), Msg_len,
Local, Server_port);
try {
Dsocket.send (Dpacket);
Sb.append ("Message sent successfully!"). Append ("n");
catch (IOException e) {
E.printstacktrace ();
Sb.append ("message sent failed."). Append ("n");
}
Dsocket.close ();
return sb.tostring ();
}

}

Main activity:

Copy Code code as follows:

public class Mainact extends activity {

EditText msg_et = null;
Button SEND_BT = null;
TextView INFO_TV = null;

@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);

Msg_et = (edittext) Findviewbyid (R.id.msg_et);
SEND_BT = (Button) Findviewbyid (R.ID.SEND_BT);
INFO_TV = (TextView) Findviewbyid (R.ID.INFO_TV);

Turn on the server
Executorservice exec = Executors.newcachedthreadpool ();
Udpserver Server = new Udpserver ();
Exec.execute (server);

Send a message
Send_bt.setonclicklistener (New Onclicklistener () {
@Override
public void OnClick (View v) {
UdpClient client = new UdpClient (Msg_et.gettext (). toString ());
Info_tv.settext (Client.send ());
}
});
}
}

Note In the configuration file you want to add:

To get the appropriate permissions.

Effect Chart:

Logcat Printed server-side information:

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.