Java NIO SocketChannel客戶端例子(支援連線失敗後自動重連)
阿新 • • 發佈:2018-12-31
這兩天想找找標題裡說的這個示例程式碼,發現網上這麼多教程,連怎麼樣實現自動重連都不講,所以把自己寫的例子貼上來。僅僅使用遞迴,不使用多執行緒,就可以實現初步的目的:
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; } } }