Skip to content

Instantly share code, notes, and snippets.

@vlaadbrain
Created September 27, 2012 04:35
Show Gist options
  • Save vlaadbrain/3792182 to your computer and use it in GitHub Desktop.
Save vlaadbrain/3792182 to your computer and use it in GitHub Desktop.
mina example
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();
}
}
@mdaftabsmu
Copy link

It is not working , Kindly check the code ????

@stodge
Copy link

stodge commented Apr 19, 2017

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