-
Notifications
You must be signed in to change notification settings - Fork 0
/
UDPServer (2).java
27 lines (22 loc) · 1.08 KB
/
UDPServer (2).java
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
import java.net.*;
public class UDPServer {
public static void main(String[] args) {
final int PORT = 9876;
try (DatagramSocket serverSocket = new DatagramSocket(PORT)) {
System.out.println("Server is listening on port " + PORT);
while (true) {
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
System.out.println("Received from client: " + message);
String response = "Server says: Hello, " + message;
byte[] sendData = response.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, receivePacket.getAddress(), receivePacket.getPort());
serverSocket.send(sendPacket);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}