001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 * 019 */ 020package org.apache.mina.example.chat.client; 021 022import org.apache.mina.core.service.IoHandler; 023import org.apache.mina.core.service.IoHandlerAdapter; 024import org.apache.mina.core.session.IoSession; 025import org.apache.mina.example.chat.ChatCommand; 026 027/** 028 * {@link IoHandler} implementation of the client side of the simple chat protocol. 029 * 030 * @author <a href="http://mina.apache.org">Apache MINA Project</a> 031 */ 032public class SwingChatClientHandler extends IoHandlerAdapter { 033 034 public interface Callback { 035 void connected(); 036 037 void loggedIn(); 038 039 void loggedOut(); 040 041 void disconnected(); 042 043 void messageReceived(String message); 044 045 void error(String message); 046 } 047 048 private final Callback callback; 049 050 public SwingChatClientHandler(Callback callback) { 051 this.callback = callback; 052 } 053 054 @Override 055 public void sessionOpened(IoSession session) throws Exception { 056 callback.connected(); 057 } 058 059 @Override 060 public void messageReceived(IoSession session, Object message) 061 throws Exception { 062 String theMessage = (String) message; 063 String[] result = theMessage.split(" ", 3); 064 String status = result[1]; 065 String theCommand = result[0]; 066 ChatCommand command = ChatCommand.valueOf(theCommand); 067 068 if ("OK".equals(status)) { 069 070 switch (command.toInt()) { 071 072 case ChatCommand.BROADCAST: 073 if (result.length == 3) { 074 callback.messageReceived(result[2]); 075 } 076 break; 077 case ChatCommand.LOGIN: 078 callback.loggedIn(); 079 break; 080 081 case ChatCommand.QUIT: 082 callback.loggedOut(); 083 break; 084 } 085 086 } else { 087 if (result.length == 3) { 088 callback.error(result[2]); 089 } 090 } 091 } 092 093 @Override 094 public void sessionClosed(IoSession session) throws Exception { 095 callback.disconnected(); 096 } 097 098}