1 20 package org.apache.mina.example.chat.client; 21 22 import org.apache.mina.common.IoFilter; 23 import org.apache.mina.common.IoHandler; 24 import org.apache.mina.common.IoHandlerAdapter; 25 import org.apache.mina.common.IoSession; 26 import org.apache.mina.example.chat.ChatCommand; 27 import org.apache.mina.filter.LoggingFilter; 28 import org.apache.mina.filter.codec.ProtocolCodecFilter; 29 import org.apache.mina.filter.codec.textline.TextLineCodecFactory; 30 31 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 IoFilter LOGGING_FILTER = new LoggingFilter(); 54 55 private static 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 public void sessionCreated(IoSession session) throws Exception { 65 session.getFilterChain().addLast("codec", CODEC_FILTER); 66 session.getFilterChain().addLast("logger", LOGGING_FILTER); 67 } 68 69 public void sessionOpened(IoSession session) throws Exception { 70 callback.connected(); 71 } 72 73 public void messageReceived(IoSession session, Object message) 74 throws Exception { 75 String theMessage = (String ) message; 76 String [] result = theMessage.split(" ", 3); 77 String status = result[1]; 78 String theCommand = result[0]; 79 ChatCommand command = ChatCommand.valueOf(theCommand); 80 81 if ("OK".equals(status)) { 82 83 switch (command.toInt()) { 84 85 case ChatCommand.BROADCAST: 86 if (result.length == 3) { 87 callback.messageReceived(result[2]); 88 } 89 break; 90 case ChatCommand.LOGIN: 91 callback.loggedIn(); 92 break; 93 94 case ChatCommand.QUIT: 95 callback.loggedOut(); 96 break; 97 } 98 99 } else { 100 if (result.length == 3) { 101 callback.error(result[2]); 102 } 103 } 104 } 105 106 public void sessionClosed(IoSession session) throws Exception { 107 callback.disconnected(); 108 } 109 110 } 111 | Popular Tags |