neusoftonline
发贴: 6
积分: 0
|
于 2004-12-13 22:29
littledeer你好,您的贴子我已读过。可能我没把意思说明白,我想实现一个能接收多个用户的服务器端,并让服务器和客户端之间能互相发送信息。现在服务器端和客户端已经做好,但是在DOS下互相传送信息还不知道从何入手,请大家指点。以下是服务器端和客户端程序: 服务器端: import java.io.*; import java.net.*;
class ServeOneJabber extends Thread { private Socket socket; private BufferedReader in; private PrintWriter out; public ServeOneJabber(Socket s) throws IOException { socket=s; in=new BufferedReader(new InputStreamReader(socket.getInputStream())); out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true); start(); } public void run() { try { while(true) { String str=in.readLine(); if(str.equals("END")) break; System.out.println("Echoing : "+str); out.println(str); } System.out.println("closing......"); } catch(IOException e) {} finally { try { socket.close(); } catch(IOException e) {} } } } public class MulitiJabberServer { static final int PORT=8080; public static void main(String[] args)throws IOException { ServerSocket s=new ServerSocket(PORT); System.out.println("Server Started"); try { while(true) { Socket socket=s.accept(); try { new ServeOneJabber(socket); } catch(IOException e) { socket.close(); } } } finally { s.close();} } }
客户端: import java.io.*; import java.net.*;
class JabberClientThread extends Thread { private Socket socket; private BufferedReader in; private PrintWriter out; private static int counter=0;//客户数量 private int id=counter++; private static int threadcount=0; public static int threadCount() { return threadcount; } public JabberClientThread(InetAddress addr) { System.out.println("Making client "+id); threadcount++;//每产生1个客户端,+1 try { socket =new Socket(addr,MulitiJabberServer.PORT); } catch(IOException e) { } try{ in=new BufferedReader(new InputStreamReader(socket.getInputStream())); //out=new PrintWriter(socket.getOutputStream); out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true); start(); } catch(IOException e) { } try { socket.close(); } catch(IOException e2){} } public void run() { try { for(int i=0;i<12;i++) { out.println("Client "+id+" :"+i); String str=in.readLine(); System.out.println(str); } out.println("END"); } catch(IOException e) {} finally { //最终总是要关闭 try { socket.close(); } catch(IOException e) {} //结束线程 threadcount--; } } } public class MultiJabberClient { static final int MAX_THREADS=40; public static void main(String[] args)throws IOException,InterruptedException { InetAddress addr=InetAddress.getByName(null); while(true) { if(JabberClientThread.threadCount()<MAX_THREADS) new JabberClientThread(addr); Thread.currentThread().sleep(100); } } }
|