需求:應用A(一般有多個)和應用B(1個)進行 socket通信,應用A必須知道應用B的ip地址(在應用A的配置文件中寫死的),這個時候就必須把應用B的ip設成固定ip(可是某些時候如更換路由後要從新設置網絡,可是操做人員不知道這個規則),就有可能形成應用A和應用B沒法進行正常通信,因此要改爲應用A動態獲取應用B的ip地址。java
通過討論決定採用udp協議實現,upd是一種無鏈接的傳輸層協議。應用A在不知道應用B的 ip狀況下 能夠使用廣播地址255.255.255.255,將消息發送到在同一廣播網絡上的B。從而獲取B的ip。網絡
實現代碼:socket
B應用爲服務端:將udp監聽放到一個線程中,當有客戶端請求時就會進行響應 /** * udp鏈接,用於動態ip, pos向255.255.255.255:5060發送請求便可 * **/ public class UdpServer extends Thread implements Runnable { private final int MAX_LENGTH = 1024; private final int PORT = 5060; private DatagramSocket datagramSocket; public void run() { try { init(); while(true){ try { byte[] buffer = new byte[MAX_LENGTH]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); receive(packet); String receStr = new String(packet.getData(), 0 , packet.getLength()); System.out.println("接收數據包" + receStr); byte[] bt = new byte[packet.getLength()]; System.arraycopy(packet.getData(), 0, bt, 0, packet.getLength()); System.out.println(packet.getAddress().getHostAddress() + ":" + packet.getPort() + ":" + Arrays.toString(bt)); packet.setData(bt); response(packet); } catch (Exception e) { e.printStackTrace(); LoggerUtil.error("udp線程出現異常:" + e.toString()); } } } catch (Exception e) { e.printStackTrace(); } } public void receive(DatagramPacket packet) throws Exception { datagramSocket.receive(packet); } public void response(DatagramPacket packet) throws Exception { datagramSocket.send(packet); } /** * 初始化鏈接 */ public void init(){ try { datagramSocket = new DatagramSocket(PORT); System.out.println("udp服務端已經啓動!"); } catch (Exception e) { datagramSocket = null; System.out.println("udp服務端啓動失敗!"); e.printStackTrace(); } } }
客戶端:原本客戶端是使用pb來實現的,可是這裏使用java來模擬 /*** * UDP Client端 ***/ public class UdpClient { private String sendStr = "hello"; private String netAddress = "255.255.255.255"; private final int PORT = 5060; private DatagramSocket datagramSocket; private DatagramPacket datagramPacket; public UdpClient(){ try { datagramSocket = new DatagramSocket(); byte[] buf = sendStr.getBytes(); InetAddress address = InetAddress.getByName(netAddress); datagramPacket = new DatagramPacket(buf, buf.length, address, PORT); datagramSocket.send(datagramPacket); byte[] receBuf = new byte[1024]; DatagramPacket recePacket = new DatagramPacket(receBuf, receBuf.length); datagramSocket.receive(recePacket); String receStr = new String(recePacket.getData(), 0 , recePacket.getLength());
//獲取服務端ip String serverIp = recePacket.getAdress(); } catch (SocketException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關閉socket if(datagramSocket != null){ datagramSocket.close(); } } } public static void main(String[] args) { for (int i = 0; i < 100; i++) { new Thread(new Runnable() { @Override public void run() { UdpClient udpClient = new UdpClient(); } }).start(); } } }