举报投诉联系我们 手机版 热门标签 鳄鱼CMS
您的位置:鳄鱼CMS > 异步套接字是什么 Java 异步套接字通道

异步套接字是什么 Java 异步套接字通道

2023-03-10 19:31 Java教程

异步套接字是什么 Java 异步套接字通道

异步套接字是什么

异步套接字是一种网络通信技术,它可以让两台计算机之间进行高效的数据传输。它使用一个双向的、可靠的、全双工的连接,以便在两台计算机之间传递数据。

异步套接字是一种非常有用的工具,它能够帮助我们在不同的计算机之间传递数据。它使用一个可靠的连接来保证数据传输的准确性和安全性。异步套接字也能够在不同的应用之间进行通信,从而使得应用能够交流信息。

// 创建异步套接字
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
// 连接到远端服务器 
socket.Connect("127.0.0.1", 8080); 
// 发送数据 
socket.Send(data); 
// 接受数据 
byte[] buffer = new byte[1024]; 
int bytesRead = socket.Receive(buffer); 

Java 异步套接字通道

Java网络教程 - Java异步套接字通道


使用以下两个套接字通道类来执行异步套接字操作:

java.nio.channels.AsynchronousServerSocketChannel
java.nio.channels.AsynchronousSocketChannel

以下代码显示如何创建使用异步服务器套接字通道的服务器应用程序。

例子

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
public class Main {
  public static void main(String[] args) throws Exception {
    AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel
        .open();
    String host = "localhost";
    int port = 8989;
    InetSocketAddress sAddr = new InetSocketAddress(host, port);
    server.bind(sAddr);
    System.out.format("Server is listening at %s%n", sAddr);
    Attachment attach = new Attachment();
    attach.server = server;
    server.accept(attach, new ConnectionHandler());
    Thread.currentThread().join();
  }
}
class Attachment {
  AsynchronousServerSocketChannel server;
  AsynchronousSocketChannel client;
  ByteBuffer buffer;
  SocketAddress clientAddr;
  boolean isRead;
}

class ConnectionHandler implements
    CompletionHandler<AsynchronousSocketChannel, Attachment> {
  @Override
  public void completed(AsynchronousSocketChannel client, Attachment attach) {
    try {
      SocketAddress clientAddr = client.getRemoteAddress();
      System.out.format("Accepted a  connection from  %s%n", clientAddr);
      attach.server.accept(attach, this);
      ReadWriteHandler rwHandler = new ReadWriteHandler();
      Attachment newAttach = new Attachment();
      newAttach.server = attach.server;
      newAttach.client = client;
      newAttach.buffer = ByteBuffer.allocate(2048);
      newAttach.isRead = true;
      newAttach.clientAddr = clientAddr;
      client.read(newAttach.buffer, newAttach, rwHandler);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override
  public void failed(Throwable e, Attachment attach) {
    System.out.println("Failed to accept a  connection.");
    e.printStackTrace();
  }
}

class ReadWriteHandler implements CompletionHandler<Integer, Attachment> {
  @Override
  public void completed(Integer result, Attachment attach) {
    if (result == -1) {
      try {
        attach.client.close();
        System.out.format("Stopped   listening to the   client %s%n",
            attach.clientAddr);
      } catch (IOException ex) {
        ex.printStackTrace();
      }
      return;
    }

    if (attach.isRead) {
      attach.buffer.flip();
      int limits = attach.buffer.limit();
      byte bytes[] = new byte[limits];
      attach.buffer.get(bytes, 0, limits);
      Charset cs = Charset.forName("UTF-8");
      String msg = new String(bytes, cs);
      System.out.format("Client at  %s  says: %s%n", attach.clientAddr,
          msg);
      attach.isRead = false; // It is a write
      attach.buffer.rewind();

    } else {
      // Write to the client
      attach.client.write(attach.buffer, attach, this);
      attach.isRead = true;
      attach.buffer.clear();
      attach.client.read(attach.buffer, attach, this);
    }
  }

  @Override
  public void failed(Throwable e, Attachment attach) {
    e.printStackTrace();
  }
}

上面的代码生成以下结果。


异步客户端套接字通道

AsynchronousSocketChannel 类用作客户端应用程序中的异步客户端套接字通道。

以下代码显示如何创建异步客户端套接字通道。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.util.concurrent.Future;

public class Main {
  public static void main(String[] args) throws Exception {
    AsynchronousSocketChannel channel = AsynchronousSocketChannel.open();
    SocketAddress serverAddr = new InetSocketAddress("localhost", 8989);
    Future<Void> result = channel.connect(serverAddr);
    result.get();
    System.out.println("Connected");
    Attachment attach = new Attachment();
    attach.channel = channel;
    attach.buffer = ByteBuffer.allocate(2048);
    attach.isRead = false;
    attach.mainThread = Thread.currentThread();

    Charset cs = Charset.forName("UTF-8");
    String msg = "Hello";
    byte[] data = msg.getBytes(cs);
    attach.buffer.put(data);
    attach.buffer.flip();

    ReadWriteHandler readWriteHandler = new ReadWriteHandler();
    channel.write(attach.buffer, attach, readWriteHandler);
    attach.mainThread.join();
  }
}
class Attachment {
  AsynchronousSocketChannel channel;
  ByteBuffer buffer;
  Thread mainThread;
  boolean isRead;
}
class ReadWriteHandler implements CompletionHandler<Integer, Attachment> {
  @Override
  public void completed(Integer result, Attachment attach) {
    if (attach.isRead) {
      attach.buffer.flip();
      Charset cs = Charset.forName("UTF-8");
      int limits = attach.buffer.limit();
      byte bytes[] = new byte[limits];
      attach.buffer.get(bytes, 0, limits);
      String msg = new String(bytes, cs);
      System.out.format("Server Responded: "+ msg);
      try {
        msg = this.getTextFromUser();
      } catch (Exception e) {
        e.printStackTrace();
      }
      if (msg.equalsIgnoreCase("bye")) {
        attach.mainThread.interrupt();
        return;
      }
      attach.buffer.clear();
      byte[] data = msg.getBytes(cs);
      attach.buffer.put(data);
      attach.buffer.flip();
      attach.isRead = false; // It is a write
      attach.channel.write(attach.buffer, attach, this);
    }else {
      attach.isRead = true;
      attach.buffer.clear();
      attach.channel.read(attach.buffer, attach, this);
    }
  }
  @Override
  public void failed(Throwable e, Attachment attach) {
    e.printStackTrace();
  }
  private String getTextFromUser() throws Exception{
    System.out.print("Please enter a  message  (Bye  to quit):");
    BufferedReader consoleReader = new BufferedReader(
        new InputStreamReader(System.in));
    String msg = consoleReader.readLine();
    return msg;
  }
}


阅读全文
以上是鳄鱼CMS为你收集整理的异步套接字是什么 Java 异步套接字通道全部内容。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。
相关文章
  • java集合foreach JavaFX 集合

    java集合foreach JavaFX 集合

    2023-03-17 Java教程

    JavaFX教程 -JavaFX集合JavaFX中的集合由javafx.collections包定义,javafx.collections包由以下接口和类组成:接口接口描述Obse...

  • java持久性 Java 实例/持续时间

    java持久性 Java 实例/持续时间

    2023-03-04 Java教程

    Java日期时间 -Java实例/持续时间实例和持续时间允许我们记录时间戳和已用时间。我们可以从瞬间添加和减去持续时间,以获得另一...

  • java 流 Java 流连接

    java 流 Java 流连接

    2023-03-08 Java教程

    Java流连接Collectors类的joining()方法返回一个收集器,它连接CharSequence流,并将结果作为String返回。joining()方法是重载的...

  • java扫描器代码 Java 扫描器

    java扫描器代码 Java 扫描器

    2023-03-09 Java教程

    Java IO教程 -Java扫描器要从标准输入读取数字,我们必须将其读取为字符串并将其解析为数字。java.util包中的Scanner类根据模式...

  • java组合框怎么设置 JavaFX 组合框

    java组合框怎么设置 JavaFX 组合框

    2023-03-06 Java教程

    JavaFX教程 -JavaFX组合框组合框允许用户选择几个选项之一。用户可以滚动到下拉列表。组合框可以是可编辑和不可编辑的。创建组合...

© 2024 鳄鱼CMS eyucms.com 版权所有 联系我们