1 /**
2 * 监听多个客户的服务器端
3 *
4 * 主程序监听一端口,等待客户接入;同时构造一个线程类,准备接管会话。
5 * 当一个Socket会话产生后,将这个会话交给线程处理,然后主程序继续监听。
6 */
7 import java.io.*;
8 import java.net.*;
9
10 public class MultiServer extends ServerSocket {
11 private static final int SERVER_PORT = 10000;
12
13 public MultiServer() throws IOException {
14 super(SERVER_PORT);
15 try {
16 while (true) {
17 Socket socket = accept();
18 new CreateServerThread(socket);
19 }
20 } catch (IOException e) {
21 } finally {
22 close();
23 }
24 }
25
26 // --- CreateServerThread
27 class CreateServerThread extends Thread {
28 private Socket client;
29 private BufferedReader in;
30 private PrintWriter out;
31
32 public CreateServerThread(Socket s) throws IOException {
33 client = s;
34 in = new BufferedReader(new InputStreamReader(
35 client.getInputStream(), "GB2312"));
36 out = new PrintWriter(client.getOutputStream(), true);
37 out.println("--- Welcome ---");
38 start();
39 }
40
41 public void run() {
42 try {
43 String line = in.readLine();
44 while (!line.equals("bye")) {
45 String msg = createMessage(line);
46 out.println(msg);
47 line = in.readLine();
48 }
49 out.println("--- See you, bye! ---");
50 client.close();
51 } catch (IOException e) {
52 }
53 }
54
55 private String createMessage(String line) {
56 // xxxxxxxxx;
57 return line;
58 }
59 }
60
61 public static void main(String[] args) throws IOException {
62 new MultiServer();
63 }
64 }