The method of realizing automatic socket connection based on LAN UDP broadcast in Android programming _android

Source: Internet
Author: User

This article describes the Android programming implementation based on LAN UDP radio to automatically establish a socket connection method. Share to everyone for your reference, specific as follows:

Socket communication is often used in Android development. As a result of the project needs, a recent study of this knowledge. The demand is to achieve file transfer and control between the Android mobile device and the Android platform's TV via WiFi. There is no doubt that the middle of this need to use a socket to communicate. Today on the two devices to shake hands to share the way, the method is only my personal ideas to achieve, only for reference, if there is a similarity, it is an honor.

To use the socket to communicate, you must know the IP address of the server, I am using the UDP network broadcast to achieve the server in the local network search and establish a connection. Here is the code implementation.

The first is the client:

public class Mainactivity extends activity {/* Send broadcast side of socket*/private MulticastSocket MS; 
 /* Send broadcast button/private button sendudpbrocast; 
  @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
 Init (); 
  /* Initialization parameter/* public void init () {Setcontentview (r.layout.main); 
  Sendudpbrocast = (Button) Findviewbyid (r.id.send); 
  Sendudpbrocast.setonclicklistener (New Sendudpbrocastlistener ()); 
  try {* * Create a Socket instance */ms = new MulticastSocket (); 
  catch (Exception e) {e.printstacktrace (); }/** * Click button, send LAN Broadcast * */class Sendudpbrocastlistener implements onclicklistener{@Override Public v 
   OID OnClick (View v) {//packets sent, all addresses within the local network can receive the packet datagrampacket datapacket = null; 
    try {ms.settimetolive (4); 
    The native IP (here can write dynamically obtained IP) address into the packet, in fact, the server received packets can also obtain the client's IP byte[] data = "192.168.1.101". GetBytes (); 224.0.0.1 for broadcast addresses inetaddress address = Inetaddress.getbyname ("224.0.0.1 "); 
    This place can be output to determine whether the address is broadcast type address System.out.println (address.ismulticastaddress ()); 
    Datapacket = new Datagrampacket (data, data.length, address, 8003); 
    Ms.send (Datapacket); 
   Ms.close (); 
   catch (Exception e) {e.printstacktrace (); 

 } 
  } 
 } 
}

The following are service-side:

public class Mainactivity extends activity implements Runnable {private MulticastSocket ds; 
 String multicasthost= "224.0.0.1"; 
 InetAddress receiveaddress; 
  @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); 
  Setcontentview (R.layout.main); 
   try {ds = new MulticastSocket (8003); 
   Receiveaddress=inetaddress.getbyname (Multicasthost); 
   Ds.joingroup (receiveaddress); 
  New Thread (This). Start (); 
  catch (Exception E1) {//TODO auto-generated catch block E1.printstacktrace (); 
  @Override public void Run () {//TODO auto-generated Method stub byte buf[] = new byte[1024]; 
  Datagrampacket DP = new Datagrampacket (buf, 1024); 
    while (true) {try {ds.receive (DP); 
    Toast.maketext (This, new String (buf, 0, Dp.getlength ()), Toast.length_long); 
   SYSTEM.OUT.PRINTLN ("Client IP:" +new String (buf, 0, Dp.getlength ()); 
   catch (Exception e) {e.printstacktrace (); 
} 
  } } 
}

 

In this way, if the mobile device is connected to the local network of sockets in the server, the server will receive the broadcast from the client, and then the server through the received IP and the client to connect and then can control and file transmission. It should be noted that UDP broadcasts cause the local network to slow down transmission, and UDP is unreliable protocol, issued by the broadcast service side may not be able to receive, so in fact, need to do a lot of logic processing, such as online Chengri broadcast until received the server response but if the local network does not exist in the service side will fall into the dead cycle, So it's time to do a limited operation and so on ... Look at the personal needs of the specific.

I hope this article will help you with the Android program.

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.