Android Automatically Establishes a socket connection through lan udp Broadcast

Source: Internet
Author: User

Socket communication is often used in Android development. Due to project requirements, I recently studied this knowledge. The requirement is to implement file transmission and control between Android mobile devices and TVs on the Android platform through WiFi.
There is no doubt that socket must be used in the middle for communication. I would like to share with you the handshake method of the two devices today. This method is just an implementation of my own ideas and is only for your reference. It would be a great honor to share it with you.

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

First, the client:

Public class mainactivity extends activity {/* Send broadcast socket */private multicastsocket MS;/* Send broadcast button */private button sendudpbrocast; @ overridepublic 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 socket instance */MS = new multicastsocket ();} catch (exception e) {e. printstacktrace () ;}}/*** when you click the button, send LAN broadcast **/class sendudpbrocastlistener implements onclicklistener {@ overridepublic void onclick (view v) {// packet sent, all the addresses in the local network can receive the packet datagrampacket datapacket = NULL; try {Ms. settimetolive (4); // place the local IP address (the IP address can be dynamically obtained here) into the data packet, in fact, after the server receives the data packet, it can also obtain the byte [] DATA = "192.168.1.101" of the packet sender's IP address ". getbytes (); // 224.0.0.1 is the broadcast address inetaddress = inetaddress. getbyname ("224.0.0.1"); // This area can be output to determine whether the address is a broadcast address system. out. println (address. ismulticastaddress (); datapacket = new datagrampacket (data, data. length, addresses, 8003); Ms. send (datapacket); Ms. close ();} catch (exception e) {e. printstacktrace ();}}}}

The following are the servers:

public class MainActivity extends Activity implements Runnable {private MulticastSocket ds;String multicastHost="224.0.0.1";InetAddress receiveAddress;@Overridepublic 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 blocke1.printStackTrace();}}@Overridepublic void run() {// TODO Auto-generated method stubbyte 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 a socket server exists in the local network connected to the mobile device, the server receives the broadcast from the client, then, the server connects to the client through the received IP address to control and transmit files. It should be noted that UDP broadcast will slow the local network transmission speed, and UDP is an unreliable protocol, which may not necessarily be received by the Broadcast Server, therefore, we need to perform a lot of logic processing in actual situations. For example, when sending a broadcast in the thread, the server will be stuck in an endless loop until it receives a response from the server, so now we have to do a limited time operation and so on... For more information, see personal requirements.


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.