Establish a TCP connection through UDP and a TCP connection through UDP
Explanation
Query the Server IP address through UDP broadcast, and then establish a TCP point-to-point connection.
Application scenarios
When the IP address of the server is unknown, it is known that the server and client are clearly in a LAN or a subnet that allows multicast. Discover the server address through UDP and then establish a TCP connection. (PS: Many vrouters on the world wide have restricted multicast. Therefore, server queries cannot be performed on the World Wide Web through UDP packets)
Main Problems
The Android real machine and simulator have restrictions on multicast processing in different Android systems and versions on multicast processing in different networks. For example, some routing networks limit UDP packets.
Simple implementation
In traditional multicast mode, full Forwarding is performed through the 255.255.255.255 address. After receiving the packet, the client checks the packet and obtains the IP address of the server from the UDP packet data. Connect to the instance through an IP address. PS: it may be a problem. For example, on the Android 5.0.1 real machine (mobile phone of your humble servant), you cannot receive packets from the 255.255.255.255 group. It may also be filtered out by the router, but everything works normally on the simulator. Solutions for real machines will be provided later
Hello message code for server broadcast:
1 private class BoadrcastDispense implements Runnable { 2 3 @Override 4 public void run() { 5 try { 6 if (UDPSocket == null) { 7 UDPSocket = new DatagramSocket(udpPortServer); 8 } 9 } catch (SocketException e1) {10 }11 while (!UDPSocket.isClosed() && flag) {12 try {13 Thread.sleep(1000);14 } catch (InterruptedException e) {15 e.printStackTrace();16 }17 try {18 // send message19 String str = "Hello Client";20 byte backData[] = str.getBytes();21 DatagramPacket backPacket = new DatagramPacket(backData,22 backData.length,23 InetAddress.getByName("255.255.255.255"),24 udpPortClient);25 UDPSocket.send(backPacket);26 } catch (SocketException e) {27 e.printStackTrace();28 } catch (IOException e) {29 e.printStackTrace();30 }31 }32 }33 34 }
The client receives the Hello message code.
1 public static boolean searchServer () {2 try {3 // receive packet 4 if (udpSocket = null) {5 udpSocket = new DatagramSocket (udpPortClient); 6 udpSocket. setSoTimeout (5000); 7} 8 byte receiveData [] = new byte [bufferSize]; 9 encrypt rampacket into epacket = new DatagramPacket (receiveData, 10 receiveData. length); 11 udpSocket. receive (receivePacket); 12 String recieveStr = new String (receivePacket. getData (), 13 bytes epacket. getOffset (), receivePacket. getLength (); 14 System. out. println ("Server IP Address:" 15 + receivePacket. getAddress (). getHostAddress (); 16 System. out. println ("received server feedback:" + recieveStr); 17 if (recieveStr. equalsIgnoreCase ("Hello Client") {18 serverIP = receivePacket. getAddress (). getHostAddress (); 19 System. out. println ("successfully connected to the server"); 20 return true; 21} 22} catch (SocketException e) {23 e. printStackTrace (); 24} catch (UnknownHostException e) {25 e. printStackTrace (); 26} catch (IOException e) {27 e. printStackTrace (); 28} 29 System. out. println ("failed to connect to the server"); 30 return false; 31 32}
When debugging on the simulator, the above Code is enough. However, when running on a real machine, it is found that it is always blocked in receive. Baidu + Google is still fruitless, and many people have encountered this problem. There are three possible reasons:
1 WifiManager manager = (WifiManager) getSystemService (Context. WIFI_SERVICE); 2 WifiManager. multicastLock lock = manager. createMulticastLock ("test wifi"); 3 lock. acquire (); 4 // The multicast operation to be executed, such as 5 locks such as receive. release ();
However, this is not the reason.
2. the routing or network device shields 255 packets.
The Wi-Fi network shields packets sent from the 255.255.255.255.255 group, but sends 255 packets in reverse transmission (Android sends packets to the PC and finds that the PC can receive the packets. Therefore, this reason is excluded. PS: This is still very likely elsewhere. Many routers have blocked 255 multicast by default to prevent broadcast storms, or restricted the number of multicast. For example, Huawei's device is limited to 30% by default, and the packet loss rate can be imagined.
3. subdomains cannot send broadcasts to external domains.
This is more theoretical. It is said that the IP address of the home router is 192.168.0.1, and 192.168.x.x belongs to the internal domain, so it cannot broadcast anything to the outside... the computer network has not learned well, and this reason is not taken into consideration for the moment.
Improvement implementation
Because various search results are fruitless, I decided to try another way of thinking. During the attempt, I was inspired by the following two solutions that Android could send 255 broadcast packets to the PC. using Android to establish a server and connect a PC to Android in reverse mode is a simple and fast P2P connection, but only a P2P connection is supported. This method is not applicable if you want the server to access multiple clients. first, obtain the Android IP address through the PC, then send the fixed-point UDP packet, and then obtain the server IP address from the fixed-point UDP packet. The advantage is that the basic PC is used as the server, and android is used as the client structure, I just need to transfer the IP address to my method. Because the server code is basically finished and I don't want to make major changes, the second method is adopted, and the code is relatively simple:
Send 255 messages to PC through Android
1 public static void sendPacktToServer() { 2 try { 3 // receive packet 4 if (udpSocket == null) { 5 udpSocket = new DatagramSocket(udpPortClient); 6 udpSocket.setSoTimeout(5000); 7 } 8 String str = "Hello Server"; 9 byte[] data = str.getBytes();10 DatagramPacket sendPacket = new DatagramPacket(data,11 data.length,12 InetAddress.getByName("255.255.255.255"), udpPortServer);13 lock.acquire();14 udpSocket.send(sendPacket);15 lock.release();16 } catch (SocketException e) {17 e.printStackTrace();18 } catch (UnknownHostException e) {19 e.printStackTrace();20 } catch (IOException e) {21 e.printStackTrace();22 }23 }
The PC side directly returns the targeted UDP packet after receiving the 255 message sent by Android, so that the Android side can receive the message and then establish a TCP connection.
1 private class BoardcastListener implements Runnable {2 3 @ Override 4 public void run () {5 try {6 if (UDPSocket = null) {7 UDPSocket = new DatagramSocket (udpPortServer ); 8} 9} catch (SocketException e1) {10} 11 while (! UDPSocket. isClosed () & flag) {12 try {13 // receive message14 byte [] recvBuf = new byte [bufferSize]; 15 minutes rampacket recvPacket = new hour rampacket (recvBuf, 16 recvBuf. length); 17 UDPSocket. receive (recvPacket); 18 String recvStr = new String (recvPacket. getData (), 0, 19 recvPacket. getLength (); 20 ServerFrame. getInstance (). appendServerStr (21 "UDP message received:" + recvStr + "from:" 22 + recvPacket. getAddress (). getHostAddress (); 23 // send back message24 String str = "Hello Client"; 25 byte backData [] = str. getBytes (); 26 bytes rampacket backPacket = new bytes rampacket (backData, 27 backData. length, recvPacket. getAddress (), 28 udpPortClient); 29 UDPSocket. send (backPacket); 30} catch (SocketException e) {31 e. printStackTrace (); 32} catch (IOException e) {33 e. printStackTrace (); 34} 35} 36} 37 38}
At this point, the basic core code has been completely pasted. Currently, after testing, both the simulator and android real machine can be connected to the server.
Summary
In fact, the main purpose is to establish a connection in the LAN without knowing the IP address of the other party. There are actually many solutions. For example, UDP interaction is used, but TCP does not require manual Stability Maintenance. Therefore, TCP connections are preferred for data transmission. (Applicable scenarios: Lan games and Internet of Things are connected to each other) It is true that you can also manually query the IP address and enter the IP address for TCP connection. However, on mobile devices, you still prefer the one-click feature. Using UDP for automatic server discovery, this feature is still a little useful ....