-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUDPServer.java
More file actions
72 lines (56 loc) · 2.6 KB
/
Copy pathUDPServer.java
File metadata and controls
72 lines (56 loc) · 2.6 KB
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
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.text.SimpleDateFormat;
import java.util.Date;
public class UDPServer extends Thread {
private DatagramSocket socket;
private byte[] buf = new byte[1024];
private Path logPath;
UDPServer(int port, String logsFile) throws IOException {
logPath = Paths.get(logsFile);
if (!Files.exists(logPath)) {
System.out.println("*** Creating log file ***");
Files.createFile(logPath);
}
System.out.println("*** Starting server on port " + port + " ***");
socket = new DatagramSocket(port);
}
public void run() {
boolean running = true;
while (running) {
try {
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
SimpleDateFormat sdfDateTime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String dStr = sdfDateTime.format(new Date());
byte[] data = new byte[packet.getLength()];
System.arraycopy(packet.getData(), packet.getOffset(), data, 0, packet.getLength());
InetAddress address = packet.getAddress();
int port = packet.getPort();
String received = new String(data, 0, data.length);
Files.write(logPath, data, StandardOpenOption.APPEND);
if (received.equals("end")) {
running = false;
continue;
}
System.out.println("[Received] [" + dStr + "] [" + address.getCanonicalHostName() + ":" + port + "] " + Utils.convertByteArrayToHexString(data));
String hexCmd = "29 29 21 00 05 BA B1 06 29 0D";
byte[] loginConfirmation = Utils.convertHexStringToByteArray(hexCmd);
DatagramPacket sendPacket = new DatagramPacket(loginConfirmation, loginConfirmation.length, address, port);
socket.send(sendPacket);
dStr = sdfDateTime.format(new Date());
System.out.println("[Sent] [" + dStr + "] [" + address.getCanonicalHostName() + ":" + port + "] " + Utils.convertByteArrayToHexString(loginConfirmation));
Files.write(logPath, loginConfirmation, StandardOpenOption.APPEND);
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}