1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.example.chat.client;
21
22 import org.apache.mina.core.filterchain.IoFilter;
23 import org.apache.mina.core.service.IoHandler;
24 import org.apache.mina.core.service.IoHandlerAdapter;
25 import org.apache.mina.core.session.IoSession;
26 import org.apache.mina.example.chat.ChatCommand;
27 import org.apache.mina.filter.codec.ProtocolCodecFilter;
28 import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
29 import org.apache.mina.filter.logging.LoggingFilter;
30
31
32
33
34
35
36
37 public class SwingChatClientHandler extends IoHandlerAdapter {
38
39 public interface Callback {
40 void connected();
41
42 void loggedIn();
43
44 void loggedOut();
45
46 void disconnected();
47
48 void messageReceived(String message);
49
50 void error(String message);
51 }
52
53 private static final IoFilter LOGGING_FILTER = new LoggingFilter();
54
55 private static final IoFilter CODEC_FILTER = new ProtocolCodecFilter(
56 new TextLineCodecFactory());
57
58 private final Callback callback;
59
60 public SwingChatClientHandler(Callback callback) {
61 this.callback = callback;
62 }
63
64 @Override
65 public void sessionCreated(IoSession session) throws Exception {
66 session.getFilterChain().addLast("codec", CODEC_FILTER);
67 session.getFilterChain().addLast("logger", LOGGING_FILTER);
68 }
69
70 @Override
71 public void sessionOpened(IoSession session) throws Exception {
72 callback.connected();
73 }
74
75 @Override
76 public void messageReceived(IoSession session, Object message)
77 throws Exception {
78 String theMessage = (String) message;
79 String[] result = theMessage.split(" ", 3);
80 String status = result[1];
81 String theCommand = result[0];
82 ChatCommand command = ChatCommand.valueOf(theCommand);
83
84 if ("OK".equals(status)) {
85
86 switch (command.toInt()) {
87
88 case ChatCommand.BROADCAST:
89 if (result.length == 3) {
90 callback.messageReceived(result[2]);
91 }
92 break;
93 case ChatCommand.LOGIN:
94 callback.loggedIn();
95 break;
96
97 case ChatCommand.QUIT:
98 callback.loggedOut();
99 break;
100 }
101
102 } else {
103 if (result.length == 3) {
104 callback.error(result[2]);
105 }
106 }
107 }
108
109 @Override
110 public void sessionClosed(IoSession session) throws Exception {
111 callback.disconnected();
112 }
113
114 }