日期:2014-05-20 浏览次数:20782 次
Java code服务端 import java.net.*; import java.io.*; import java.util.*; class fanserver { static List<fanclient> client = new ArrayList<fanclient>(); public static void main(String[] args)throws Exception { Socket s; ServerSocket ss = new ServerSocket(4445); while(true){ s = ss.accept(); System.out.println("haha..."); server ser = new server(s); new Thread(ser).start(); client.add(ser); } /* BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bwout = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); BufferedReader brin = new BufferedReader(new InputStreamReader(s.getInputStream())); String str = null; while((str=brin.readLine())!=null){ // System.out.println(str); bwout.write(str); bwout.flush(); bwout.newLine(); } */ // s.shutdownOutput(); } } class server implements Runnable { private Socket s; server(Socket s){ this.s = s; } public void run(){ try{ BufferedWriter bwout = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); BufferedReader brin = new BufferedReader(new InputStreamReader(s.getInputStream())); String str = null; while((str=brin.readLine())!=null){ System.out.println(str); bwout.write(str); bwout.newLine(); bwout.flush(); } // s.shutdownOutput(); } catch(Exception e){} } } Java code客户端 import java.net.*; import java.io.*; class fanclient { public static void main(String[] args)throws Exception { Socket s = new Socket("192.168.30.129",4445); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bwout = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); BufferedReader brin = new BufferedReader(new InputStreamReader(s.getInputStream())); new Thread(new client(brin)).start(); String str = null; while((str=br.readLine())!=null){ bwout.write(str); bwout.newLine(); bwout.flush(); } // s.shutdownOutput(); // String line = brin.readLine(); // System.out.println(line); } } class client implements Runnable { private BufferedReader brin; client(BufferedReader brin) { this.brin = brin; } public void run(){ String line = null; try{ while((line=brin.readLine())!=null){ System.out.println(line); } }catch(Exception e){} } } 我同时启动好几个客户端,想让客户端通过服无端互相接收到信息,怎么处理,