1 20 package org.apache.mina.example.sumup; 21 22 import java.net.InetSocketAddress ; 23 24 import org.apache.mina.common.ConnectFuture; 25 import org.apache.mina.common.IoSession; 26 import org.apache.mina.common.RuntimeIOException; 27 import org.apache.mina.example.sumup.codec.SumUpProtocolCodecFactory; 28 import org.apache.mina.filter.LoggingFilter; 29 import org.apache.mina.filter.codec.ProtocolCodecFilter; 30 import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory; 31 import org.apache.mina.transport.socket.nio.SocketConnector; 32 import org.apache.mina.transport.socket.nio.SocketConnectorConfig; 33 34 40 public class Client { 41 private static final String HOSTNAME = "localhost"; 42 43 private static final int PORT = 8080; 44 45 private static final int CONNECT_TIMEOUT = 30; 47 private static final boolean USE_CUSTOM_CODEC = true; 49 50 public static void main(String [] args) throws Throwable { 51 if (args.length == 0) { 52 System.out.println("Please specify the list of any integers"); 53 return; 54 } 55 56 int[] values = new int[args.length]; 58 for (int i = 0; i < args.length; i++) { 59 values[i] = Integer.parseInt(args[i]); 60 } 61 62 SocketConnector connector = new SocketConnector(); 63 64 connector.setWorkerTimeout(1); 67 68 SocketConnectorConfig cfg = new SocketConnectorConfig(); 70 cfg.setConnectTimeout(CONNECT_TIMEOUT); 71 if (USE_CUSTOM_CODEC) { 72 cfg.getFilterChain().addLast( 73 "codec", 74 new ProtocolCodecFilter( 75 new SumUpProtocolCodecFactory(false))); 76 } else { 77 cfg.getFilterChain().addLast( 78 "codec", 79 new ProtocolCodecFilter( 80 new ObjectSerializationCodecFactory())); 81 } 82 cfg.getFilterChain().addLast("logger", new LoggingFilter()); 83 84 IoSession session; 85 for (;;) { 86 try { 87 ConnectFuture future = connector.connect(new InetSocketAddress ( 88 HOSTNAME, PORT), new ClientSessionHandler(values), cfg); 89 90 future.join(); 91 session = future.getSession(); 92 break; 93 } catch (RuntimeIOException e) { 94 System.err.println("Failed to connect."); 95 e.printStackTrace(); 96 Thread.sleep(5000); 97 } 98 } 99 100 session.getCloseFuture().join(); 102 } 103 } 104 | Popular Tags |