集册 Java实例教程 使用AsynchronousServerSocketChannel类管理异步通信

使用AsynchronousServerSocketChannel类管理异步通信

欢马劈雪     最近更新时间:2020-01-02 10:19:05

355
使用AsynchronousServerSocketChannel类管理异步通信
/*来 自 nowjava - 时代Java*/

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.AsynchronousSocketChannel;

import java.util.Scanner;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.Future;


public class Main {

  

    public static void main(String[] args) {

        try {

            AsynchronousSocketChannel client = AsynchronousSocketChannel.open();

            InetSocketAddress address = new InetSocketAddress("localhost", 5000);


            Future<Void> future = client.connect(address);
            /**来自 
             NowJava.com - 时代Java**/

            System.out.println("Client: Waiting for the connection to complete");

            future.get();


            String message = "";

            while(!message.equals("quit")) {

                System.out.print("Enter a message: ");

                Scanner scanner = new Scanner(System.in);

                message = scanner.nextLine();

                System.out.println("Client: Sending ...");

                ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());

                System.out.println(
展开阅读全文