日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java异步通信实现

發布時間:2025/3/21 java 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java异步通信实现 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

參考鏈接:

[1] java aio 編程

[2] java AIO 服務端代碼實現

主要內容:

實現服務端、客戶端異步多次通信。

服務端代碼:

package com.aio;import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousServerSocketChannel; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.nio.charset.Charset; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException;/*** java AIO 服務端代碼實現* https://blog.csdn.net/qq_29048719/article/details/81045258*/ public class AIOServer {public final static int PORT = 9888;private AsynchronousServerSocketChannel server;private AsynchronousSocketChannel lastClient; // 最后一次連接的客戶端public AIOServer() throws IOException {server = AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(PORT));}/*** Future方式* @throws InterruptedException* @throws ExecutionException* @throws TimeoutException*/public void startWithFuture() throws InterruptedException,ExecutionException, TimeoutException {while (true) {// 循環接收客戶端請求Future<AsynchronousSocketChannel> future = server.accept();AsynchronousSocketChannel socket = future.get();// get() 是為了確保 accept 到一個連接handleWithFuture(socket);}}public void handleWithFuture(AsynchronousSocketChannel channel) throws InterruptedException, ExecutionException, TimeoutException {ByteBuffer readBuf = ByteBuffer.allocate(2);readBuf.clear();while (true) {// 一次可能讀不完//get 是為了確保 read 完成,超時時間可以有效避免DOS攻擊,如果客戶端一直不發送數據,則進行超時處理Integer integer = channel.read(readBuf).get(100000, TimeUnit.SECONDS);System.out.println("read: " + integer);if (integer == -1) {break;}readBuf.flip();System.out.println("received: " + Charset.forName("UTF-8").decode(readBuf));readBuf.clear();}}/*** Callback方式* @throws InterruptedException* @throws ExecutionException* @throws TimeoutException*/public void startWithCompletionHandler() throws InterruptedException,ExecutionException, TimeoutException {server.accept(null,new CompletionHandler<AsynchronousSocketChannel, Object>() {public void completed(AsynchronousSocketChannel result, Object attachment) {server.accept(null, this);// 再次接收客戶端連接handleWithCompletionHandler(result);lastClient = result;}@Overridepublic void failed(Throwable exc, Object attachment) {exc.printStackTrace();}});}public void handleWithCompletionHandler(final AsynchronousSocketChannel channel) {try {final ByteBuffer buffer = ByteBuffer.allocate(2048);final long timeout = 30L;channel.read(buffer, timeout, TimeUnit.MINUTES, null, new CompletionHandler<Integer, Object>() {@Overridepublic void completed(Integer result, Object attachment) {System.out.println("read:" + result);if (result == -1) {try {channel.close();} catch (IOException e) {e.printStackTrace();}return;}buffer.flip();System.out.println("received message from client:" + Charset.forName("UTF-8").decode(buffer));buffer.clear();// 再次等待讀取客戶端消息channel.read(buffer, timeout, TimeUnit.MINUTES, null, this);}@Overridepublic void failed(Throwable exc, Object attachment) {exc.printStackTrace();}});} catch (Exception e) {e.printStackTrace();}}public static void main(String args[]) throws Exception {// new AIOServer().startWithFuture();AIOServer aioServer = new AIOServer();// 使用Callback方式aioServer.startWithCompletionHandler();Thread.sleep(20000);aioServer.lastClient.write(ByteBuffer.wrap("服務端消息1".getBytes()));Thread.sleep(1000);aioServer.lastClient.write(ByteBuffer.wrap("服務端消息2".getBytes()));Thread.sleep(100000);} }

客戶端代碼:

package com.aio;import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.InetSocketAddress; import java.net.Socket; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousServerSocketChannel; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.nio.charset.Charset; import java.util.Scanner; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException;public class AIOClient {public final static int PORT = 9888;private AsynchronousSocketChannel asyncClient;public AIOClient() throws IOException {asyncClient = AsynchronousSocketChannel.open();}public void startWithFuture() throws InterruptedException, ExecutionException {asyncClient.connect(new InetSocketAddress("localhost", PORT)).get();handleWithCompletionHandler();}public void handleWithCompletionHandler() {try {final ByteBuffer buffer = ByteBuffer.allocate(2048);asyncClient.read(buffer, null, new CompletionHandler<Integer, Object>() {@Overridepublic void completed(Integer result, Object attachment) {System.out.println("read:" + result);if (result == -1) {return;}buffer.flip();System.out.println("received message from server:" + Charset.forName("UTF-8").decode(buffer));buffer.clear();// 再次等待讀取服務端消息asyncClient.read(buffer, null, this);}@Overridepublic void failed(Throwable exc, Object attachment) {exc.printStackTrace();}});} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) throws IOException, ExecutionException, InterruptedException {// AsynchronousSocketChannel client = AsynchronousSocketChannel.open();// client.connect(new InetSocketAddress("localhost", 9888)).get();// client.write(ByteBuffer.wrap("123456789".getBytes()));// Thread.sleep(1000);// client.write(ByteBuffer.wrap("32165498".getBytes()));// Thread.sleep(1111111);AIOClient aioClient = new AIOClient();aioClient.startWithFuture();aioClient.asyncClient.write(ByteBuffer.wrap("123456789".getBytes()));Thread.sleep(1000);aioClient.asyncClient.write(ByteBuffer.wrap("32165498".getBytes()));Thread.sleep(200000);} }

結果輸出:

AIOServer

Connected to the target VM, address: '127.0.0.1:63937', transport: 'socket' read:9 received message from client:123456789 read:8 received message from client:32165498

AIOClient

Connected to the target VM, address: '127.0.0.1:63946', transport: 'socket' read:16 received message from server:服務端消息1 read:16 received message from server:服務端消息2

總結

以上是生活随笔為你收集整理的Java异步通信实现的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。