Created
September 27, 2012 04:35
-
-
Save vlaadbrain/3792182 to your computer and use it in GitHub Desktop.
mina example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.InetSocketAddress; | |
import java.nio.charset.Charset; | |
import org.apache.mina.core.RuntimeIoException; | |
import org.apache.mina.core.future.ConnectFuture; | |
import org.apache.mina.core.service.IoHandlerAdapter; | |
import org.apache.mina.core.session.IoSession; | |
import org.apache.mina.filter.codec.ProtocolCodecFilter; | |
import org.apache.mina.filter.codec.textline.TextLineCodecFactory; | |
import org.apache.mina.filter.logging.LoggingFilter; | |
import org.apache.mina.transport.socket.nio.NioSocketConnector; | |
public class MinaExampleClient extends IoHandlerAdapter { | |
private String [] SYMBOLS = new String[]{"SPY", "BAC", "XOM"}; | |
private void subscribe(IoSession session) { | |
for (String symbol : SYMBOLS) | |
session.write('w' + symbol); | |
} | |
private void processQuote(String ... fields) {} | |
@Override | |
public void messageReceived(IoSession session, Object message) | |
throws Exception { | |
String [] fields = message.toString().split(","); | |
if (fields.length > 0) { | |
if (fields[0].equals("Q")) { | |
this.processQuote(fields); | |
} else if (fields[0].equals("S")) { | |
if (fields[1].equals("CUST")) | |
this.subscribe(session); | |
} | |
} | |
} | |
public static void main(String [] args) { | |
NioSocketConnector connector = new NioSocketConnector(); | |
connector.setConnectTimeoutMillis(10*1000L); | |
connector.getFilterChain().addLast("ascii", | |
new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("US-ASCII")))); | |
connector.getFilterChain().addLast("logger", new LoggingFilter()); | |
connector.setHandler(new MinaExampleClient()); | |
IoSession session; | |
for (;;) { | |
try { | |
ConnectFuture future = connector.connect(new InetSocketAddress("localhost", 5009)); | |
future.awaitUninterruptibly(); | |
session = future.getSession(); | |
break; | |
} catch (RuntimeIoException e) { | |
System.err.println("Failed to connect."); | |
e.printStackTrace(); | |
try { | |
Thread.sleep(10); | |
} catch (InterruptedException i) {} | |
} | |
} | |
session.getCloseFuture().awaitUninterruptibly(); | |
connector.dispose(); | |
} | |
} |
How would you change this to reconnect to the server when the connection is lost?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It is not working , Kindly check the code ????