-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUDPClient.java
More file actions
28 lines (24 loc) · 880 Bytes
/
Copy pathUDPClient.java
File metadata and controls
28 lines (24 loc) · 880 Bytes
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
package javaNetUDP;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
public class UDPClient {
public static void main(String[] args) throws Exception {
InetAddress addr = InetAddress.getByName("localhost");
try (DatagramSocket sock = new DatagramSocket()) {
sock.connect(addr, 9090);
byte[] data = "time".getBytes(StandardCharsets.UTF_8);
DatagramPacket packet = new DatagramPacket(data, data.length);
sock.send(packet);
System.out.println("Data was sent");
Thread.sleep(1000);
byte[] buffer = new byte[1024];
DatagramPacket resp = new DatagramPacket(buffer, buffer.length);
sock.receive(resp);
byte[] respData = resp.getData();
String respText = new String(respData, 0, resp.getLength());
System.out.println("Response: " + respText);
}
}
}