Android automatically establishes socket connection via LAN UDP broadcast

Source: Internet
Author: User

socket communication is often used in Android development. As a result of the project, we have recently studied this knowledge. The requirement is to realize the file transfer and control between the Android mobile device and the Android platform TV via WiFi. There is no doubt that the socket must be used to communicate. Today on the two devices to share the handshake connection, the method is just my personal idea of the realization, for reference only, if there is similar, it is honored.

To use the socket for communication, you must know the IP address of the server, I use UDP network broadcast to achieve the network service side of the search to establish a connection. The following is the code implementation.

The first is the client:

 Public classMainactivity extends Activity {/*send the socket on the broadcast side*/    PrivateMulticastSocket MS; /*send a broadcast button*/    PrivateButton Sendudpbrocast; @Override Public voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);    Init (); }        /*Initialize Parameters*/     Public voidinit () {Setcontentview (r.layout.main); Sendudpbrocast=(Button) Findviewbyid (r.id.send); Sendudpbrocast.setonclicklistener (NewSendudpbrocastlistener ()); Try {            /*creating a Socket instance*/Ms=NewMulticastSocket (); } Catch(Exception e) {e.printstacktrace (); }    }        /** * When clicking the button, send LAN broadcast **/    classSendudpbrocastlistener implements onclicklistener{@Override Public voidOnClick (View v) {//send the packet, all the addresses within the network can receive the packetDatagrampacket Datapacket =NULL; Try{ms.settimetolive (4); //The IP of this machine (which can write dynamically acquired IP) address in the packet, in fact, the server side received the packet can also get to the employer's IP                byte[] data ="192.168.1.101". GetBytes (); //224.0.0.1 for broadcast addressInetAddress address = Inetaddress.getbyname ("224.0.0.1"); //This place can output an address that determines whether the address is a broadcast type.System. out. println (Address.ismulticastaddress ()); Datapacket=Newdatagrampacket (data, data.length, address,8003);                Ms.send (Datapacket);            Ms.close (); } Catch(Exception e) {e.printstacktrace (); }        }    }}

The following are the service side:

 Public classMainactivity extends Activity implements Runnable {PrivateMulticastSocket ds; String Multicasthost="224.0.0.1";    InetAddress receiveaddress; @Override Public voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.main); Try{DS=NewMulticastSocket (8003); Receiveaddress=Inetaddress.getbyname (multicasthost);            Ds.joingroup (receiveaddress); NewThread ( This). Start (); } Catch(Exception E1) {//TODO auto-generated Catch blockE1.printstacktrace (); }} @Override Public voidrun () {//TODO auto-generated Method Stub        byteBuf[] =New byte[1024x768]; Datagrampacket DP=NewDatagrampacket (BUF,1024x768);  while(true) {            Try{ds.receive (DP); //Toast.maketext (This, new String (buf, 0, Dp.getlength ()), toast.length_long);System. out. println ("Client IP:"+NewString (BUF,0, Dp.getlength ())); } Catch(Exception e) {e.printstacktrace (); }        }    }}

In this way, if the mobile device is connected to the local network socket server, the server will receive a broadcast from the client, and then the server and the received IP to connect with the client and then you can control and file transmission. It is important to note that the UDP broadcast will cause the network transmission speed is slow, and UDP is unreliable protocol, issued by the broadcast service end may not be able to receive, so in the actual situation need to do a lot of logic processing, such as online thread broadcast to receive the service side of the response but if the network does not exist in the service end will be trapped in a So we're going to do a time-limited operation,

Android automatically establishes socket connection via LAN UDP broadcast

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.