Repository navigation
Expand file tree
/
Copy pathJavaUdpServer.java
More file actions
72 lines (51 loc) · 2.16 KB
/
Copy pathJavaUdpServer.java
File metadata and controls
72 lines (51 loc) · 2.16 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.util.Date;
/*
reference:
https://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html
*/
public class JavaUdpServer {
static UdpServerThread udpServerThread;
public static void main(String[] args) throws IOException {
System.out.println("Server start");
System.out.println("Runtime Java: "
+ System.getProperty("java.runtime.version"));
new UdpServerThread().start();
}
private static class UdpServerThread extends Thread{
final int serverport = 4445;
protected DatagramSocket socket = null;
public UdpServerThread() throws IOException {
this("UdpServerThread");
}
public UdpServerThread(String name) throws IOException {
super(name);
socket = new DatagramSocket(serverport);
System.out.println("JavaUdpServer run on: " + serverport);
}
@Override
public void run() {
while(true){
try {
byte[] buf = new byte[256];
// receive request
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String dString = new Date().toString();
buf = dString.getBytes();
// send the response to the client at "address" and "port"
InetAddress address = packet.getAddress();
int port = packet.getPort();
System.out.println("Request from: " + address + ":" + port);
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);
} catch (IOException ex) {
System.out.println(ex.toString());
}
}
}
}
}