Blame view

C5/testproject/src/main/java/com/sunvote/udptest/LocalUDPDataSender.java 2.35 KB
fac86401   孙向锦   初始化C5 Vote
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
  package com.sunvote.udptest;
  
  import java.net.DatagramSocket;
  import java.net.InetAddress;
  
  /**
   * Created by Elvis on 2017/8/8.
   * Email:Eluis@psunsky.com
   * Description:
   */
  
  public class LocalUDPDataSender {
  
      private final static String TAG = LocalUDPDataSender.class.getSimpleName();
  
      private static LocalUDPDataSender instance = null;
  
      private DatagramSocket remoteUDPSocket = null;
  
  
      public static LocalUDPDataSender getInstance() {
          if (instance == null)
              instance = new LocalUDPDataSender();
          return instance;
      }
  
      private LocalUDPDataSender() {
  
      }
  
      public DatagramSocket resetRemoteUDPSocket() {
          try {
              closeLocalUDPSocket();
              remoteUDPSocket = (MainActivity.port ==  0 ?
                      new DatagramSocket() : new DatagramSocket(MainActivity.port));//_Utils.LOCAL_UDP_SEND$LISTENING_PORT);
              remoteUDPSocket.setReuseAddress(true);
              return remoteUDPSocket;
          } catch (Exception e) {
              closeLocalUDPSocket();
              return null;
          }
      }
  
      private boolean isRemoteUDPSocketReady() {
          boolean ret = true;
          if(remoteUDPSocket != null) {
              return ret && !remoteUDPSocket.isClosed();
          }
          return false;
      }
  
  
  
      public void closeLocalUDPSocket() {
          try {
              if (remoteUDPSocket != null) {
                  remoteUDPSocket.close();
                  remoteUDPSocket = null;
              } else {
              }
          } catch (Exception e) {
          }
      }
  
      public DatagramSocket getRemoteDPSocket() {
          if (isRemoteUDPSocketReady()) {
              return remoteUDPSocket;
          } else {
              return resetRemoteUDPSocket();
          }
      }
  
  
  
      /**
       * 需要重载一个函数
       * 如果没有指定服务器IP地址,则只能广播出去,让服务器接收处理
       * @param fullProtocalBytes
       * @param dataLen
       * @return
       */
      public int send(byte[] fullProtocalBytes, int dataLen) {
          DatagramSocket ds = getRemoteDPSocket();
          if (ds != null && !ds.isConnected()) {
              try {
                  ds.connect(InetAddress.getByName(MainActivity.serverIp), MainActivity.port);
              } catch (Exception e) {
                  return -1;
              }
          }
          return UDPUtils.send(ds, fullProtocalBytes, dataLen) ? 0 : -1;
  
      }
  
  
  }