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

📄 datagramadditionclient.java

📁 程序练习中包括书中实例程序代码和练习中要用到的代码,是压缩文件
💻 JAVA
字号:
package examples.network;

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

/** A client-side class that uses a datagram socket
  */
public class DatagramAdditionClient {

   private InetAddress host;
   private int port;

   // This is not a reserved port number 
   static final int DEFAULT_PORT = 8189; 

   /** Constructor
     * @param host Internet address of the host
     *        where the server is located
     * @param port Port number on the host where
     *        the server is listening
     */
   public DatagramAdditionClient( InetAddress host,
                          int port ) {
      this.host = host;
      this.port = port;
   }

   /** The method used to start a client object
     */
   public void run() {
      try {
         DatagramSocket client = new DatagramSocket();

         String numbers = "1.2 3.4 5.6";
         DatagramPacket outDgp
            = new DatagramPacket( numbers.getBytes(),
                                  numbers.length(),
                                  host,
                                  port );
         client.send( outDgp );
         System.out.println( "Adding the numbers "
                             + numbers + " together" );
         byte[] buffer = new byte[256];
         DatagramPacket inDgp
            = new DatagramPacket( buffer,
                                  buffer.length );
         client.receive( inDgp );
         String rsp = new String( inDgp.getData(), 0,
                                  inDgp.getLength() );
         System.out.println( rsp );

         String quit = "";
         outDgp.setData( quit.getBytes() );
         outDgp.setLength( quit.length() );
         client.send( outDgp );
         client.close();
      }
      catch( IOException iox ) {
         System.out.println( iox );
         iox.printStackTrace();
      }
   }

   /** The test method for the class
     * @param args Optional port number
     *        and host name
     */
   public static void main( String[] args ) {
      try {
         InetAddress host = InetAddress.getLocalHost();
         int port = DEFAULT_PORT;
         if ( args.length > 0 ) {
            port = Integer.parseInt( args[0] );
         }
         if ( args.length > 1 ) {
            host = InetAddress.getByName( args[1] );
         }

         DatagramAdditionClient addClient
            = new DatagramAdditionClient( host, port );
         addClient.run();
      }
      catch ( UnknownHostException uhx ) {
         System.out.println( uhx );
         uhx.printStackTrace();
      }
   }
}

⌨️ 快捷键说明

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