http://www.verejava.com/?id=16994896966324
服务器端 package com.tcp; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class Browser { public static void main(String[] args) { try { ServerSocket ss=new ServerSocket(8888); System.out.println("服务器在 8888 监听。。。"); while(true) { Socket socket=ss.accept(); InputStream is=socket.getInputStream(); byte[] b=new byte[1024]; int l=is.read(b); String message=new String(b,0,l); System.out.println(message); PrintWriter pw=new PrintWriter(socket.getOutputStream(),true); pw.println("<h1>hello</h1>"); } } catch (IOException e) { e.printStackTrace(); } } } 客户端 package com.tcp; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; public class IE { public static void main(String[] args) throws Exception { Socket socket=new Socket("localhost",8888); PrintWriter pw=new PrintWriter(socket.getOutputStream(),true); pw.println("GET /1.html / HTTP/1.1"); pw.println("Accept: */*"); pw.println("Host: localhost:8888"); pw.println("Connection: Keep-Alive"); pw.println(""); BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream())); String str=null; while((str=br.readLine())!=null) { System.out.println(str); } } }