📄 udpechoserver.java
字号:
// Sample Java Program// UDP Echo Server//// Based partially on the code in TCP/IP Sockets in Java, by Calvert and Donahoo//// Requires a single command line arg - the port number//// You can test this using nc (netcat) in UDP mode as the client:// nc -u hostname portimport java.net.*; // need this for InetAddress, Socket, ServerSocketimport java.io.*; // need this for I/O stuff public class UDPEchoServer { // define a constant used as size of buffer static final int BUFSIZE=1024; // main starts things rolling // declare main as throwing a SocketException, this means we let // Java deal with this exception (it is thrown to the calling, // and in this case the calling is the JVM). static public void main(String args[]) throws SocketException { if (args.length != 1) { throw new IllegalArgumentException("Must specify a port!"); } int port = Integer.parseInt(args[0]); // Create UDP socket DatagramSocket s = new DatagramSocket(port); // Create Datagrampacket we can use for receiving DatagramPacket dp = new DatagramPacket(new byte[BUFSIZE], BUFSIZE); try { while (true) { // wait for incoming datagram, put into dp s.receive(dp); // print out client's address System.out.println("Message from " + dp.getAddress().getHostAddress()); // Send it right back s.send(dp); dp.setLength(BUFSIZE); // avoid shrinking the packet buffer } } catch (IOException e) { System.out.println("Fatal I/O Error !"); System.exit(0); } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -