rjyang
发贴: 9
积分: 0
|
于 2005-03-08 16:38
服务器程序: import java.io.*; import java.net.*; public class Server3 extends Thread { Socket socket1; public Server3(Socket s) { socket1=s; start();//Calls run() } public void run() { try { BufferedReader in=new BufferedReader(new InputStreamReader(socket1.getInputStream())); PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket1.getOutputStream()))); for(int i=0;i<5;i++) { String str=in.readLine(); System.out.println("Server receives"+str); out.println("Server return back"+str); } System.out.println("closing..."); } catch(IOException e) { System.err.println("IOException"); } finally { try { socket1.close(); } catch(IOException e) { System.err.println("Socket not closed"); } } } static final int PORT=8000; public static void main(String[] args) throws IOException { ServerSocket s=new ServerSocket(PORT); System.out.println("Server Stared"); try { while(true) { Socket socket1=s.accept(); try { new Server3(socket1); } catch(Exception e) { socket1.close(); } } } finally { s.close(); } } }
客户端程序: import java.net.*; import java.io.*; public class Client3 extends Thread { int threadNumber; Socket socket1; public Client3(int i,Socket s) { System.out.println("Making thread="+i); threadNumber=i; socket1=s; start(); } public void run() { try { PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket1.getOutputStream())),true); BufferedReader in=new BufferedReader(new InputStreamReader(socket1.getInputStream())); for(int i=0;i<5;i++) { out.println("data from client:" + threadNumber + "=" + i); //for(int i=0;i<5;i++) String str=in.readLine(); System.out.println(str); } } catch(IOException e) { try { socket1.close(); } catch(IOException e2){} } } public static void main(String[] args)throws IOException { for(int i=1;i<11;i++) { new Client3(i,new Socket(args[0],Integer.parseInt(args[1]))); //new Client3(2,new Socket(args[0],Integer.parseInt(args[1]))); } } }
|