complete16_4.java

来自「程序练习中包括书中实例程序代码和练习中要用到的代码,是压缩文件」· Java 代码 · 共 70 行

JAVA
70
字号
package questions.c16;

import java.io.*;
import java.net.*;
import java.util.StringTokenizer;

public class Complete16_4 {

   private static final int PORT = 8189;
   private static boolean keepGoing = true;

   public static class Server extends Thread {
      public void run() {
         try {
            System.out.println( "Server starting..." );
            ServerSocket ss = new ServerSocket( PORT );
            Socket incoming = ss.accept();
            InputStream is = incoming.getInputStream();
            InputStreamReader isr = new InputStreamReader( is );
            BufferedReader in = new BufferedReader( isr );
            OutputStream os = incoming.getOutputStream();
            PrintWriter out = new PrintWriter( os );

            String str = in.readLine();
            while( str != null ) {
               System.out.println( "Received> " + str );
               str = in.readLine();
            }
            incoming.close();
         }
         catch( IOException iox ) {
            System.out.println( iox );
         }
      }
   }

  public static class Client extends Thread {
      public void run() {
         PrintWriter out = null;
         try {
            System.out.println( "Client starting..." );
            InetAddress target = InetAddress.getLocalHost();
            Socket client = new Socket( target, PORT );
            OutputStream os = client.getOutputStream();
            out = new PrintWriter( os );

            int count = 1;
            while ( keepGoing ) {
               out.println( "Message " + count++ );
               out.flush();
               Thread.currentThread().sleep( 1000 );
            }
         } catch( Exception x ) {
            System.out.println( x );
         } finally {
            if ( out != null ) {
               out.close();
            }
         }
      }
   }

   public static void requestStop() {
      keepGoing = false;
   }

   public static void main( String[] args ) {
      // Your code here
   }
}

⌨️ 快捷键说明

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