在前文“Java网络通信程序(一对一)”基础上,实现了一个服务器为多个客户端提供服务的功能,本文基于[1]之10.3.9节例10-4和10-5,修正了一些变量递增错误,删去了两个无用的变量。本文使用的客户端程序与前文完全相同。 MultiTalkServer.java倒数第6行代码表明代码中可以直接使用同一目录下其他public类(这里是ServerThread类),无需import。 [1] 陈明:Java语言程序设计,清华大学出版社,2009.6
MultiTalkServer.java import java.io.; import java.net.; public class MultiTalkServer{ static int clientNum = 1; public static void main(String args[]) throws IOException { ServerSocket serverSocket = null; boolean listening = true; try { serverSocket = new ServerSocket(4700); System.out.println("MultiTalkServer Started.\n"); } catch (IOException e){ System.out.println("Could not listen to port 4700."); System.exit(-1); } while (listening) { new ServerThread(serverSocket.accept(), clientNum).start(); //直接引用同一文件夹下的其他公共类 clientNum++; } serverSocket.close(); } }
ServerThread.java import java.io.; import java.net.; public class ServerThread extends Thread { Socket socket = null; int clientNum; public ServerThread(Socket socket, int num){ this.socket = socket; clientNum = num; } public void run(){ try{ String line; BufferedReader is = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter os = new PrintWriter(socket.getOutputStream()); System.out.println("Connected to Client #"+clientNum+"."); System.out.println(); do{ line = is.readLine(); System.out.println("Client #"+clientNum+" says: "+line); System.out.println(" To Client"+clientNum+": you said: "+line); System.out.println(); os.println("You said: "+line); os.flush(); } while (! line.equals("bye")); os.close(); is.close(); socket.close(); } catch (Exception e){ System.out.println("Error:"+e); } } }