package net; import java.net.*; import java.io.*; /** * 编写一个Java网络应用程序,该应用分服务器端程序和客户端程序两部分。 * 服务器程序启动后,监听端口5678的请求;客户端程序启动后,向服务器端口5678发送请求。 * 服务器不断接收客户机所写入的信息,并且服务器也会做出"Receive"为回应, * 告知客户机已接收到消息。要求:服务器程序采用多线程开发,允许多个客户端程序同时连接。 * 客户机发送"End"字符串时,客户端程序退出。 * (服务端程序和客户端程序分别命名为Server.java和Client.java) * @since 2010-9-28 * @start 3:00 * @end 4:49 * */ public class TwentyFive_MsgServer { public static void main(String[] args){ MsgServer server=new MsgServer(); MsgClient client=new MsgClient(); MsgClient client2=new MsgClient(); try{ server.init(); server.start(); client.setName("E3"); client.init(); client.start(); Thread.sleep(1000); client2.setName("f22"); client2.init(); client2.start(); } catch(Exception e){ e.printStackTrace(); } } } class MsgServer{ DatagramSocket ds=null; Thread t=null; ServerSocket ss=null; Socket s=null; ServerHandleThead thread=null; public void init()throws Exception{ ss=new ServerSocket(5678); } public void start(){ t=new Thread(){ public void run(){ while(true){ try{ s=ss.accept(); ServerHandleThead thread=new ServerHandleThead(s); thread.start(); } catch(Exception e){ e.printStackTrace(); } } } }; t.start(); } } class ServerHandleThead extends Thread{ Socket s=null; ServerHandleThead(Socket s){ this.s=s; } public void run(){ try{ InputStreamReader isr=new InputStreamReader(s.getInputStream()); BufferedReader br=new BufferedReader(isr); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); System.out.println("Server wait for msg..."); String str=br.readLine(); while(str!=null&&str.length()>0){ System.out.println("Server received from `"+s.getRemoteSocketAddress()); System.out.println(""+str); bw.write("Receive"); if(str.startsWith("End")){ s.close(); this.destroy(); } str=br.readLine(); } } catch(Exception e){ e.printStackTrace(); } } } class MsgClient{ Socket s=null; BufferedWriter bw=null; BufferedReader br=null; String name=""; public void setName(String name){ this.name=name; } public void init()throws Exception{ //s=new Socket(InetAddress.getLocalHost(),5678); s=new Socket("127.0.0.1",5678);//the client can auto use free port bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); br=new BufferedReader(new InputStreamReader(s.getInputStream())); } public void start(){ Thread t=new Thread(){ public void run() { for(int i=0;i<10;i++){ try{ Thread.sleep(1000); bw.write(i+"/r/n"); bw.flush(); } catch(Exception e){ e.printStackTrace(); } System.out.println(name+"`send ` "+i); } try{ bw.write("End"); bw.flush(); } catch(Exception e2){ e2.printStackTrace(); } } }; t.start(); } }