日期:2014-05-20 浏览次数:20710 次
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class MockServer { private ServerSocket socket; private int port; public MockServer(int port) { this.port = port; } public void startServer() { InputStream is = null; try { try { socket = new ServerSocket(port); // 建立服务器,端口号为port Socket inSocket = socket.accept(); // 检测端口直到与用户建立连接完成 System.out.println("与用户建立连接完成"); OutputStream os = inSocket.getOutputStream(); // 打开输出流 is = inSocket.getInputStream(); // 打开输入流 Scanner in = new Scanner(is); PrintWriter pw = new PrintWriter(os, true); // 往服务器发送数据 pw .println("<html><body>欢迎光临chelson的服务器,键入exit断开与服务器的连接</body><html>"); boolean exit = false; // 等待客户端发送数据 while (!exit && in.hasNextLine()) { String input = in.nextLine(); pw.println("您刚才输入的信息是" + input); // 返回客户端数据 if (input.trim().equals("exit")) // 如果用户输入exit就终止服务器 exit = true; } } catch (IOException e) { e.printStackTrace(); } finally { is.close(); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { MockServer server = new MockServer(23); server.startServer(); } }