原帖在:http://www.coo8ger.com/?p=141
服务器端代码:
import java.io.*; import java.net.*; public class MyServer { public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(5678); Socket client = server.accept(); BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); PrintWriter out = new PrintWriter(client.getOutputStream()); while(true) { String str = in.readLine(); System.out.println(str); out.println("has receive..."); out.flush(); if(str.equals("end")) break; } } }
客户端代码:
import java.net.*; import java.io.*; public class Client { static Socket server; public static void main(String[] args) throws Exception { server = new Socket(InetAddress.getLocalHost(), 5678); BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream())); PrintWriter out = new PrintWriter(server.getOutputStream()); BufferedReader wt = new BufferedReader(new InputStreamReader(System.in)); while(true) { String str = wt.readLine(); out.println(str); out.flush(); if(str.equals("end")) { break; } System.out.println(in.readLine()); } server.close(); } }
演示: