⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 echoudpclient.java

📁 21天学通java的示例程序源代码
💻 JAVA
字号:
package com.wrox;

import java.net.*;
import java.io.*;

/** Static methods implementing the RFC 862 UDP echo protocol client */
public class EchoUDPClient {

  /** Standard UDP echo service port defined in RFC 862 (port=7) */
  public static final int STANDARD_ECHO_PORT = 7;

  /** Default number of tries to receive an echo response from a server */
  public static final int DEFAULT_TRIES = 3;
  
  /** Default polling expiration in milliseconds  */
  public static final int DEFAULT_EXPIRE_MILLIS = 2000;

  /** Maximum UDP payload size to be sent or received */
  public static final int MAX_UDP_BUFFER_SIZE = 508;

  /** Counter used to generate unique Echo requests */
  protected static int nextRequestID= 0;

  /** Prevent instantiation (only static methods offerred) */
  private EchoUDPClient() {
  }

  /**
   * Returns true if the host is running a UDP echo service in the 
   * specified port number and successfully returned an exact copy
   * of a test message transmitted.
   * <p>
   * The service is polled up to <code>tries</code> times, with
   * <code>pollMillis</code> in between polls.
   *
   * @param address - the UDP echo service address
   * @param port    - the UDP echo service port
   * @param tries   - number of echo tries before failure
   * @param pollMillis - number of milliseconds for poll expiration
   *
   * @exception IOException - if the UDP socket could not be created
   * @exception SecurityException - if the security manager did not
   *                                permit the network operations
   */
  public static boolean echo(InetAddress address,
                             int port,
                             int tries,
                             int pollExpireMillis)
    throws IOException, SecurityException {

    if (address == null)
      throw new NullPointerException("null echo server address argument");

    // Generate a unique request ID
    long outValue;
    synchronized(EchoUDPClient.class) {
      outValue = nextRequestID;
      nextRequestID++;
    }

    // Create request packet payload (write current time to byte array)
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    DataOutputStream dataOut = new DataOutputStream(byteOut);
    try {
      dataOut.writeLong(outValue);
      dataOut.close();
    } catch (IOException e) {
      throw new RuntimeException("Unexpected I/O exception:" + e);
    }
    
    // Create datagram packet out of request
    DatagramPacket outPacket =
      new DatagramPacket(byteOut.toByteArray(),
                         byteOut.size(),
                         address, port);
    
    DatagramPacket inPacket = new DatagramPacket
      (new byte[MAX_UDP_BUFFER_SIZE], MAX_UDP_BUFFER_SIZE);

    // Create and configure socket
    DatagramSocket socket = new DatagramSocket();
    socket.setSoTimeout(pollExpireMillis);

    try {
      // Loop "tries" times sending the UDP packet and waiting for
      // notification of receipt, or expiration of the poll time.
      for(int i=0; i<tries; i++) {
        // Send packet to the world (IOException propagated to caller)
        socket.send(outPacket);
        
        // Block for reply, or timeout (as InterruptedIOException)
        try {
          socket.receive(inPacket);
        } catch (InterruptedIOException e) {
          // ignore (loop back to try again)
	  continue;
        } catch (IOException e) {
          // receive I/O errors are not propagated to the caller
          continue;
        }

        // Convert byte-array  reply into Java Unicode string
        ByteArrayInputStream byteIn = 
          new ByteArrayInputStream(inPacket.getData(),
                                   0, inPacket.getLength());
        DataInputStream dataIn =
          new DataInputStream(byteIn);
        
        try {
          long inValue = dataIn.readLong();
          
          // Verify that the values match
          if (outValue == inValue) {
            return(true);
          }
        } catch (IOException e) {
          // message was not a long value (loop back to try again)
        }

        // We're looping back so reset the inPacket buffer length
        // (we must do so every time we reuse a DatagramPacket
        //  instance for a DatagramSocket.receive() invocation)
        inPacket.setLength(MAX_UDP_BUFFER_SIZE);
      } // for (each try)
    } finally {
      try { socket.close(); } catch (Throwable e) { }
    }

    return(false);
  } // echo()

  /** Command-line utility for performing UDP echo requests. */
  public static void main(String[] args) {
    if ( (args.length == 0) || (args.length > 2) ) {
      System.err.println("Usage: EchoUDPClient <host> {<port>}");
      System.exit(1);
    }

    InetAddress address = null;
    try {
      address = InetAddress.getByName(args[0]);
    } catch (UnknownHostException e) {
      System.err.println("EchoUDPClient: unknown host " + args[0]);
      System.exit(1);
    }

    int port = STANDARD_ECHO_PORT;
    if (args.length > 1) {
      try {
        port = Integer.parseInt(args[1]);
      } catch (NumberFormatException e) {
        System.err.println("EchoUDPClient: invalid port number " + args[1]);
        System.exit(1);
      }
    }
    
    try {
      if (echo(address, port, DEFAULT_TRIES, DEFAULT_EXPIRE_MILLIS)) {
        System.out.println("Echo service active on " + address);
      } else {
        System.out.println("No echo reply from " + address);
      } 
      System.exit(0);
    } catch (Throwable e) {
      System.err.println("EchoUDPClient: " + e);
      System.exit(1);
    }
  } // main
} // EchoUDPClient

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -