ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

NIO之SocketChannel

2022-02-20 12:01:01  阅读:162  来源: 互联网

标签:NIO System socketChannel println import SocketChannel out


1、服务端

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class ServerSocketChannelDemo {
  public static void main(String[] args) throws IOException {
    //端口号
    int port = 8888;
    //buffer
    ByteBuffer buffer = ByteBuffer.wrap("hello atguigu".getBytes());
    //ServerSocketChannel
    ServerSocketChannel ssc = ServerSocketChannel.open();
    //绑定
    ssc.socket().bind(new InetSocketAddress(port));
    //设置非阻塞模式
    ssc.configureBlocking(true);
    //监听是否有新的连接传入
    while (true) {
      System.out.println("Waiting for connections");
      SocketChannel sc = ssc.accept();
      if (sc == null) {
        System.out.println("null");
      } else {
        System.out.println("Incoming connection from: " + sc.socket().getRemoteSocketAddress());
        buffer.rewind();//指针0
        sc.write(buffer);
        sc.close();
      }
    }
  }
}

2、客户端

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class SocketChannelDemo {
  public static void main(String[] args) throws IOException {
    SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8888));
    // 测试SocketChannel是否为open状态
    System.out.println("是否为open状态:" + socketChannel.isOpen());
    //测试SocketChannel是否已经被连接
    System.out.println("是否已连接:" + socketChannel.isConnected());
    //测试SocketChannel是否正在进行连接
    System.out.println("是否正在连接:" + socketChannel.isConnectionPending());
    //校验正在进行套接字连接的SocketChannel是否已经完成连接
    System.out.println("是否已完成连接:" + socketChannel.finishConnect());

    socketChannel.configureBlocking(false);
    ByteBuffer byteBuffer = ByteBuffer.allocate(16);


    int bytesRead = socketChannel.read(byteBuffer);
    while (bytesRead != -1) {
      System.out.println("读取:" + bytesRead);
      byteBuffer.flip();
      while (byteBuffer.hasRemaining()) {
        System.out.print((char) byteBuffer.get());
      }
      byteBuffer.clear();
      bytesRead = socketChannel.read(byteBuffer);
    }

    socketChannel.close();

    System.out.println("read over");

  }
}

标签:NIO,System,socketChannel,println,import,SocketChannel,out
来源: https://www.cnblogs.com/xl4ng/p/15915183.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有