MCPcopy Create free account
hub / github.com/ZTFtrue/My-note / MainActivity

Class MainActivity

java/SendHexDataByUDP.java:13–79  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

11import java.net.InetSocketAddress;
12
13public class MainActivity extends AppCompatActivity implements View.OnClickListener {
14
15 private final static String host = "125.125.125.125";
16 private final static String data = "11 11 11 11 11 11 11 11";
17 private final static int port = 8080;
18 private DatagramSocket mSocket;
19
20 @Override
21 protected void onCreate(Bundle savedInstanceState) {
22 super.onCreate(savedInstanceState);
23 setContentView(R.layout.activity_main);
24 findViewById(R.id.send).setOnClickListener(this);
25 }
26
27 @Override
28 public void onClick(View view) {
29 switch (view.getId()) {
30 case R.id.send:
31 new Thread(() -> {
32 sendData(data, port, host);
33 }).start();
34 break;
35 default:
36 break;
37 }
38 }
39
40 public void sendData(String data, int port, String... hosts) {
41 try {
42 mSocket = new DatagramSocket();
43 for (String host : hosts) {
44 InetSocketAddress address = new InetSocketAddress(host, port);
45 byte[] sendData = hexStrToByteArrs(data);
46 DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address);
47 mSocket.send(sendPacket);
48 }
49 } catch (Exception e) {
50 e.printStackTrace();
51 } finally {
52 if (mSocket != null) {
53 mSocket.close();
54 }
55 }
56 }
57
58 /**
59 * 将十六进制的字符串转换成字节数组
60 *
61 * @param hexString 字符串
62 * @return 字节
63 */
64 public static byte[] hexStrToByteArrs(String hexString) /* throws NullPointerException */ {
65 if (TextUtils.isEmpty(hexString)) {
66 throw new NullPointerException("字符串为空");
67 }
68 hexString = hexString.replaceAll(" ", "");
69 int len = hexString.length();
70 int index = 0;

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected