java nio 连接超时_Java NIO SocketChannel客户端例子(支持连接失败后自动重连)

这两天想找找标题里说的这个示例代码,发现网上这么多教程,连怎么样实现自动重连都不讲,所以把自己写的例子贴上来。仅仅使用递归,不使用多线程,就可以实现初步的目的:

import java.io.IOException;

import java.net.ConnectException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.SelectionKey;

import java.nio.channels.Selector;

import java.nio.channels.SocketChannel;

import java.util.Timer;

public class NIOClient {

// 信道选择器

private Selector selector;

// 与服务器通信的信道

SocketChannel socketChannel;

// 要连接的服务器IP地址

private String hostIp;

// 要连接的远程服务器在监听的端口

private int hostListenningPort;

private static boolean timeTocken=false;

private static Timer timer = new Timer();

private static boolean timerSet=false;

/**

* 构造函数

*

* @param HostIp

* @param HostListenningPort

* @throws IOException

*/

public NIOClient(String HostIp, int HostListenningPort) throws IOException {

this.hostIp = HostIp;

this.hostListenningPort = HostListenningPort;

initialize();

}

private void initialize() throws IOException {

// 打开监听信道并设置为非阻塞模式

try{

socketChannel = SocketChannel.open(new InetSocketAddress(hostIp,

hostListenningPort));

}

catch(ConnectException e){

System.out.println("Error happened when establishing connection, try again 5s later");

try {

Thread.sleep(5000);

} catch (InterruptedException e1) {

e1.printStackTrace();

}

if(!timerSet){

timer.schedule(new SetTocken(), 15000);

timerSet=true;

}

if(!timeTocken){

initialize();

}

return;

}

socketChannel.configureBlocking(false);

// 打开并注册选择器到信道

selector = Selector.open();

socketChannel.register(selector, SelectionKey.OP_READ);

}

/**

* 发送字符串到服务器

*

* @param message

* @throws IOException

*/

public void sendMsg(String message) throws IOException {

ByteBuffer writeBuffer = ByteBuffer.wrap(message.getBytes("UTF-8"));

socketChannel.write(writeBuffer);

}

public static void main(String[] args) throws IOException {

NIOClient client = new NIOClient("127.0.0.1", 12000);

client.sendMsg("This is a NIOClient, testing");

client.end();

timer.cancel();

}

private void end() {

// TODO Auto-generated method stub

try {

socketChannel.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

static class SetTocken extends java.util.TimerTask {

@Override

public void run() {

// TODO Auto-generated method stub

timeTocken=true;

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值