DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

java programmer from china Nile has posted 6 posts at DZone. View Full User Profile

TcpMockServer

03.23.2010
| 812 views |
  • submit to reddit
        测试用的 TCP Server类

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;

public class TcpMockServer
{
  ServerSocket server;
  DataOutputStream output;
  Socket socket;

  public TcpMockServer(int port)
  {
    try
    {
      this.server = new ServerSocket(port);

      System.out.println("Server created.");
      System.out.println("waiting for client to connect on...");

      this.socket = this.server.accept();

      System.out.println("client connected.\nShutdown!");
      InputStream outputStream = this.socket.getInputStream();
      BufferedReader br = new BufferedReader(
        new InputStreamReader(outputStream));
      String l = null;
      do {
        l = br.readLine();
        if (l != null)
          System.out.println(l); 
      }
      while (l != null);
      this.output.close();
      this.server.close();
    } catch (SocketException e) {
      System.out.println("连接关闭");
      System.exit(0);
    } catch (IOException e) {
      System.out.println("连接关闭");
      System.exit(0);
    } finally {
      System.out.println("连接关闭");
    }
  }

  public static void main(String[] args) {
    System.out.println(args[0]);
    TcpMockServer game = new TcpMockServer(Integer.parseInt(args[0]));
  }
}