|
1 | 1 | package ir.xenoncommunity.utils;
|
2 | 2 |
|
3 | 3 | import ir.xenoncommunity.Main;
|
4 |
| -import lombok.SneakyThrows; |
5 | 4 | import lombok.val;
|
| 5 | + |
| 6 | +import java.net.DatagramSocket; |
| 7 | +import java.net.InetAddress; |
6 | 8 | import java.net.Socket;
|
7 | 9 |
|
8 | 10 | public class SocketUtils {
|
9 |
| - @SneakyThrows |
10 |
| - public void connect(final String ipIn, final int port, final boolean sendResult, final boolean keepAlive){ |
11 |
| - try(val socket = new Socket(ipIn, port)){ |
12 |
| - Main.runner.getLogger().setSection("CONNECT"); |
13 |
| - if (sendResult && socket.isConnected()) { |
14 |
| - Main.runner.getLogger().print(Logger.LEVEL. INFO, String.format("Connected! ip: %s, port: %s, threads: %s\n", ipIn, port, Main.runner.getTaskManager().tasks.size())); |
15 |
| - } |
16 |
| - if (keepAlive) { |
17 |
| - socket.setKeepAlive(true); |
18 |
| - } else{ |
19 |
| - socket.close(); |
| 11 | + public void connect(final String ipAddress, final int port, final boolean sendResult, final boolean keepAlive, final boolean udp) { |
| 12 | + Main.runner.getLogger().setSection("CONNECT"); |
| 13 | + try { |
| 14 | + if (udp) { |
| 15 | + if (keepAlive) { |
| 16 | + Main.runner.getLogger().print(Logger.LEVEL.ERROR, "Can't use keepAlive for UDP protocol."); |
| 17 | + throw new IllegalStateException("UDP is used with keepAlive."); |
| 18 | + } |
| 19 | + try (val socket = new DatagramSocket(port, InetAddress.getByName(ipAddress))) { |
| 20 | + if (sendResult && socket.isConnected()) { |
| 21 | + Main.runner.getLogger().print(Logger.LEVEL.INFO, String.format("Connected! ip: %s, port: %s, threads: %s\n", ipAddress, port, Main.runner.getTaskManager().tasks.size())); |
| 22 | + } |
| 23 | + } |
| 24 | + } else { |
| 25 | + try (val socket = new Socket(ipAddress, port)) { |
| 26 | + if (sendResult && socket.isConnected()) { |
| 27 | + Main.runner.getLogger().print(Logger.LEVEL.INFO, String.format("Connected! ip: %s, port: %s, threads: %s\n", ipAddress, port, Main.runner.getTaskManager().tasks.size())); |
| 28 | + } |
| 29 | + if (keepAlive) { |
| 30 | + socket.setKeepAlive(true); |
| 31 | + } else |
| 32 | + socket.close(); |
| 33 | + } |
20 | 34 | }
|
| 35 | + } catch (final Exception e) { |
| 36 | + Main.runner.getLogger().print(Logger.LEVEL.ERROR, e.getMessage()); |
21 | 37 | }
|
22 | 38 | }
|
23 | 39 | }
|
0 commit comments