2012年5月10日 星期四



SimpleServer:

import java.net.*;
import java.io.*;
public class SimpleServer {
   public final static int myPort=20; // 使用port 20
   public static void main(String args[]) {
      //ServerSocket ss; 
      //Socket sc;
      PrintWriter op;
      try {
      ServerSocket ss = new ServerSocket(myPort);
       while (true) {
      Socket sc = ss.accept(); // 等待建立連線

op = new PrintWriter(sc.getOutputStream());
 op.println("Hi! There!");
  op.flush(); // 很重要, 不要漏掉

      sc.close();
      //break; 
       }
      }
       catch (IOException e) {

  System.err.println(e);
  }

      System.out.println("end");




/*
 try {
    ss = new ServerSocket(myPort);
    try {
      while (true) {
  sc = ss.accept(); // 等待建立連線
  op = new PrintWriter(sc.getOutputStream());
  op.println("Hi! There!");
  op.flush(); // 很重要, 不要漏掉
  sc.close();
  }
    }
    catch (IOException e) {
  ss.close();
  System.err.println(e);
  }
 }
 catch (IOException e) {
  System.err.println(e);
  }


*/


}


}



MyClient:

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

public class MyClient {
  public static final int SERVICE_PORT = 20;

  public static void main(String args[]) {
    // Check for hostname parameter
    if (args.length != 1) {
      System.out.println ("Syntax - DaytimeClient host");
      return;
    }

    // Get the hostname of server
    String hostname = args[0];

    try {
      // Get a socket to the daytime service
      Socket daytime = new Socket (hostname, SERVICE_PORT);

      System.out.println ("Connection established");

      // Set the socket option just in case server stalls
      daytime.setSoTimeout ( 2000 );

      // Read from the server
      BufferedReader reader = new BufferedReader (
      new InputStreamReader(daytime.getInputStream()));

      System.out.println ("Results : " + reader.readLine());

      // Close the connection
      daytime.close();
    } catch (IOException ioe) {
      System.err.println ("Error " + ioe);
    }
  }
}




沒有留言:

張貼留言