集册 Java实例教程 使用SocketChannel编写阻塞的TCP客户端

使用SocketChannel编写阻塞的TCP客户端

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

458
为面向流的连接套接字创建一个可选通道。

import java.io.IOException;

import java.net.InetSocketAddress;

import java.net.StandardSocketOptions;

import java.nio.ByteBuffer;
/*
来 自*
 N o  w  J a v a . c o m - 时  代  Java
*/

import java.nio.CharBuffer;

import java.nio.channels.SocketChannel;

import java.nio.charset.Charset;

import java.nio.charset.CharsetDecoder;


public class Main {

  public static void main(String[] args) {

    ByteBuffer buffer = ByteBuffer.allocateDirect(1024);

    ByteBuffer helloBuffer = ByteBuffer.wrap("Hello !".getBytes());

    Charset charset = Charset.defaultCharset();/*n o w j a v a . c o m 提供*/

    CharsetDecoder decoder = charset.newDecoder();

    try (SocketChannel socketChannel = SocketChannel.open()) {

      if (socketChannel.isOpen()) {

        socketChannel.configureBlocking(true);

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

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

        socketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, true);

        socketChannel.setOption(StandardSocketOptions.SO_LINGER, 5);

        socketChannel.connect(new InetSocketAddress("127.0.0.1", 5555));

        if (socketChannel.isConnected()) {

          socketChannel.write(helloBuffer);

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

            buffer.flip();

            CharBuffer charBuffer = decoder.decode(buffer);

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

            if (buffer.hasRemaining()) {

              buffer.compact();

            } else {

              buffer.clear();

            }

            socketChannel.write(ByteBuffer.wrap("test".getBytes()));

 
展开阅读全文