集册 Java实例教程 写入套接字客户端SocketChannel

写入套接字客户端SocketChannel

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

464
编写Socket客户端SocketChannel
/*nowjava.com - 时代Java 提供*/

import java.io.IOException;

import java.net.StandardSocketOptions;

import java.nio.ByteBuffer;

import java.nio.CharBuffer;

import java.nio.channels.SelectionKey;

import java.nio.channels.Selector;

import java.nio.channels.SocketChannel;

import java.nio.charset.Charset;

import java.nio.charset.CharsetDecoder;

import java.util.Iterator;

import java.util.Random;

import java.util.Set;


public class Main {

  public static void main(String[] args) {

    ByteBuffer buffer = ByteBuffer.allocateDirect(2 * 1024);

    Charset charset = Charset.defaultCharset();

    CharsetDecoder decoder = charset.newDecoder();

    try (Selector selector = Selector.open();

        SocketChannel socketChannel = SocketChannel.open()) {

      if ((socketChannel.isOpen()) && (selector.isOpen())) {

        socketChannel.configureBlocking(false);
        /** 
        来 自 
        时代Java - N o w  J a v a . c o m
        **/

        socketChannel.setOption(StandardSocketOptions.SO_RCVBUF, 128 * 1024);

        socketChannel.setOption(StandardSocketOptions.SO_SNDBUF, 128 * 1024);

        socketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);

        socketChannel.register(selector, SelectionKey.OP_CONNECT);

        socketChannel.connect(new java.net.InetSocketAddress("127.0.0.1", 4444));

        System.out.println("Localhost: " + socketChannel.getLocalAddress());

        while (selector.select(1000) > 0) {

          Set keys = selector.selectedKeys();

          Iterator its = keys.iterator();

          while (its.hasNext()) {

            SelectionKey key = (SelectionKey) its.next();

            its.remove();

            try (SocketChannel keySocketChannel = (SocketChannel) key.channel()) {

              if (key.isConnectable()) {

                System.out.println("I am connected!");

                if (keySocketChannel.isConnectionPending()) {

                  keySocketChannel.finishConnect();

                }

                while (keySocketChannel.read(buffer) != -1) {

                  buffer.flip();

                  CharBuffer charBuffer = decoder.decode(buffer);

                  System.out.println(charBuffer.toString());

                  if (buffer.hasRemaining()) {

                    buffer.compact();

                  } else {

                    buffer.clear();

                  }

          
展开阅读全文