里边我构造了一个Message接口:
1 package testmutithreadserver.old;
2
3 /**
4 * 通用消息接口
5 *
6 * @author zhangjun
7 *
8 */
9 public interface Message {
10
11 void execute();
12
13 }
14
以及实现了一个测试消息类:
1 package testmutithreadserver.old;
2
3 import java.io.BufferedReader;
4 import java.io.IOException;
5 import java.io.InputStreamReader;
6 import java.io.PrintWriter;
7 import java.net.Socket;
8
9 /**
10 * 测试消息
11 *
12 * @author zhangjun
13 *
14 */
15 public class TestMessage implements Message {
16
17 private Socket socket;
18
19 public TestMessage(Socket socket) {
20 this.socket = socket;
21 }
22
23 @Override
24 public void execute() {
25 try {
26 BufferedReader in = new BufferedReader(new InputStreamReader(socket
27 .getInputStream()));
28 PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
29 String s;
30 while ((s = in.readLine()) != null) {
31 System.out.println("received message:" + s);
32 if (s.equals("quit")) {
33 break;
34 }
35 out.println("hello " + s);
36 }
37 } catch (IOException e) {
38 e.printStackTrace();
39 } finally {
40 try {
41 if (!socket.isClosed()) {
42 socket.close();
43 }
44 } catch (IOException e) {
45 }
46 }
47 }
48
49 }
50
代码很简单,就不用多解释什么了。下一步打算用nio在自己写个非阻塞的服务器。
简单多线程服务器实现(4)
内容版权声明:除非注明,否则皆为本站原创文章。