mina NioSocketConnector tcp客户端

2016-05-08 22:22:00
admin
原创 4859
摘要:mina NioSocketConnector tcp客户端

一、代码示例

setConnectTimeoutMillis:

1 tcp有效值范围,最小30毫秒,最大1000毫秒,默认值1000毫秒。

2 udp有效值范围同上面,但udp设置好像没效果,怀疑是本地udp能立即检测到失败,但还是建议设置。


代码下载:MinaTimeClient.java TimeClientHandler.java


import java.net.*;
import java.nio.charset.*;
import org.apache.mina.core.future.*;
import org.apache.mina.filter.codec.*;
import org.apache.mina.filter.codec.textline.*;
import org.apache.mina.filter.logging.*;
import org.apache.mina.transport.socket.nio.*;

public class MinaTimeClient {

public static final long TIMEOUT = 30; //超时设置有效果,有效值范围,最小30毫秒,最大1000毫秒,默认值1000毫秒。

public static void configClient(NioSocketConnector connector) {
connector.getFilterChain().addLast("logger", new LoggingFilter());
connector.getFilterChain().addLast("codec",
new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));

connector.setConnectTimeoutMillis(TIMEOUT);
connector.setHandler(new TimeClientHandler());
}

public static void main(String[] args) {
NioSocketConnector connector = new NioSocketConnector();
configClient(connector);

ConnectFuture cf = connector.connect(new InetSocketAddress("127.0.0.1", 9123));
cf.awaitUninterruptibly();
System.out.println("connected: " + cf.isConnected());
if (!cf.isConnected()) {
connector.dispose();
return;
}

cf.getSession().write("Hi Server!");
cf.getSession().write("quit");

cf.getSession().getCloseFuture().awaitUninterruptibly();
connector.dispose();
}
}

发表评论
评论通过审核之后才会显示。