1 20 package org.apache.mina.example.chat.client; 21 22 import java.net.SocketAddress ; 23 24 import javax.net.ssl.SSLContext; 25 26 import org.apache.mina.common.ConnectFuture; 27 import org.apache.mina.common.IoHandler; 28 import org.apache.mina.common.IoSession; 29 import org.apache.mina.example.echoserver.ssl.BogusSSLContextFactory; 30 import org.apache.mina.filter.SSLFilter; 31 import org.apache.mina.transport.socket.nio.SocketConnector; 32 import org.apache.mina.transport.socket.nio.SocketConnectorConfig; 33 34 40 public class ChatClientSupport { 41 private final IoHandler handler; 42 43 private final String name; 44 45 private IoSession session; 46 47 public ChatClientSupport(String name, IoHandler handler) { 48 if (name == null) { 49 throw new IllegalArgumentException ("Name can not be null"); 50 } 51 this.name = name; 52 this.handler = handler; 53 } 54 55 public boolean connect(SocketConnector connector, SocketAddress address, 56 boolean useSsl) { 57 if (session != null && session.isConnected()) { 58 throw new IllegalStateException ( 59 "Already connected. Disconnect first."); 60 } 61 62 try { 63 64 SocketConnectorConfig config = new SocketConnectorConfig(); 65 if (useSsl) { 66 SSLContext sslContext = BogusSSLContextFactory 67 .getInstance(false); 68 SSLFilter sslFilter = new SSLFilter(sslContext); 69 sslFilter.setUseClientMode(true); 70 config.getFilterChain().addLast("sslFilter", sslFilter); 71 } 72 73 ConnectFuture future1 = connector.connect(address, handler, config); 74 future1.join(); 75 if (!future1.isConnected()) { 76 return false; 77 } 78 session = future1.getSession(); 79 session.write("LOGIN " + name); 80 return true; 81 } catch (Exception e) { 82 e.printStackTrace(); 83 return false; 84 } 85 } 86 87 public void broadcast(String message) { 88 session.write("BROADCAST " + message); 89 } 90 91 public void quit() { 92 if (session != null) { 93 if (session.isConnected()) { 94 session.write("QUIT"); 95 session.getCloseFuture().join(); 97 } 98 session.close(); 99 } 100 } 101 102 } 103 | Popular Tags |