ex2
This commit is contained in:
52
src/Ex2/Server.java
Normal file
52
src/Ex2/Server.java
Normal file
@@ -0,0 +1,52 @@
|
||||
package Ex2;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.DatagramPacket;
|
||||
import java.net.DatagramSocket;
|
||||
import java.net.InetAddress;
|
||||
import java.net.SocketException;
|
||||
import java.time.Instant;
|
||||
|
||||
public class Server {
|
||||
|
||||
private final DatagramSocket socket;
|
||||
|
||||
public Server(int port) throws SocketException {
|
||||
this.socket = new DatagramSocket(port);
|
||||
new Thread(this::readMessages).start();
|
||||
}
|
||||
|
||||
public int getPort() {
|
||||
return this.socket.getLocalPort();
|
||||
}
|
||||
|
||||
private void sendMessage(String message, InetAddress address, int port) throws IOException {
|
||||
byte[] buffer = message.getBytes();
|
||||
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, port);
|
||||
this.socket.send(packet);
|
||||
}
|
||||
|
||||
private void processMessage(DatagramPacket packet) throws IOException {
|
||||
Instant tPrime1 = Instant.now();
|
||||
String message = new String(packet.getData(), 0, packet.getLength());
|
||||
System.out.println("[Server] Message recieved : " + message);
|
||||
Instant t1 = Instant.parse(message);
|
||||
Instant tPrime2 = Instant.now();
|
||||
sendMessage(t1.toString() + " " + tPrime1.toString() + " " + tPrime2.toString(), packet.getAddress(), packet.getPort());
|
||||
}
|
||||
|
||||
private void readMessages() {
|
||||
while (true) {
|
||||
byte[] buffer = new byte[1024];
|
||||
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
|
||||
try {
|
||||
this.socket.receive(packet);
|
||||
processMessage(packet);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user