java实现udp通讯的代码

时间:2021-11-24 00:11:46

需求:应用a(通常有多个)和应用b(1个)进行 socket通讯,应用a必须知道应用b的ip地址(在应用a的配置文件中写死的),这个时候就必须把应用b的ip设成固定ip(但是某些时候如更换路由后要重新设置网络,但是操作人员不知道这个规则),就有可能造成应用a和应用b无法进行正常通讯,所以要改成应用a动态获取应用b的ip地址。

经过讨论决定采用udp协议实现,upd是一种无连接的传输层协议。应用a在不知道应用b的 ip情况下 可以使用广播地址255.255.255.255,将消息发送到在同一广播网络上的b。从而获取b的ip。

实现代码:

b应用为服务端:将udp监听放到一个线程中,当有客户端请求时就会进行响应

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
 * 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来模拟

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/***
 * 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();
    }
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/coderising/p/9689619.html