📄 echoudpserver.java
字号:
package com.wrox;
import java.net.*;
import java.io.*;
/** Server implementing the RFC 862 UDP echo protocol */
public class EchoUDPServer extends Thread {
/** Standard UDP echo service port defined in RFC 862 (port=7) */
public static int STANDARD_ECHO_PORT = 7;
/** Default number of milliseconds between termination checks */
public static int DEFAULT_TERMINATION_CHECK_MILLIS = 5000;
/** The maximum UDP data length possible (in bytes) */
public static int MAX_UDP_DATA_LENGTH = 65508;
/** UDP socket used to receive echo requests */
protected DatagramSocket socket;
/** Controls execution of the datagram receive thread */
protected boolean isActive;
/**
* Constructs an RFC 862 UDP Echo Protocol server
*
* @param port - the UDP port number used for binding
* @exception SocketException - if the UDP datagram socket creation fails
* @exception SecurityException - if permission to accept connections
* is refused by the security manager.
*/
public EchoUDPServer(int port) throws SocketException {
super("EchoServer(" + port + ")");
socket = new DatagramSocket(port);
socket.setSoTimeout(DEFAULT_TERMINATION_CHECK_MILLIS);
isActive = true;
start();
}
/** Requests asynchronous termination of the receiving thread */
public void terminate() {
isActive = false;
}
/**
* Main thread receives and immediately sends back any data received.
* <p>
* Loop termination controlled by the terminate() method.
*/
public void run() {
System.out.println("Echo server bound to port " +
socket.getLocalPort());
DatagramPacket receivePacket =
new DatagramPacket(new byte[MAX_UDP_DATA_LENGTH],
MAX_UDP_DATA_LENGTH);
while(isActive) {
try {
// Reset the receivePacket length to the byte array length
receivePacket.setLength(MAX_UDP_DATA_LENGTH);
// Wait to receive echo request (may also time-out)
socket.receive(receivePacket);
// We just send the packet back to the sender (already marked in
// the packet by the receive method)
socket.send(receivePacket);
} catch (InterruptedIOException e) {
// ignore (used to check for termination)
} catch (Throwable e) {
// ignore
}
}
try { socket.close(); } catch (Throwable e) { }
}
/** Command-line utility for performing UDP echo requests. */
public static void main(String[] args) {
if (args.length > 1) {
System.err.println("Usage: EchoUDPServer { <port> }");
System.exit(1);
}
int port = STANDARD_ECHO_PORT;
if (args.length == 1) {
try {
port = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("EchoUDPServer: invalid port number " + args[0]);
System.exit(1);
}
}
try {
EchoUDPServer server = new EchoUDPServer(port);
server.join();
} catch (Throwable e) {
System.err.println("EchoUDPServer: " + e);
System.exit(1);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -