ICode9

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

基于nio的ScoktChannel数据传输

2021-07-13 10:30:21  阅读:171  来源: 互联网

标签:nio SocketChannel readBuffer ScoktChannel ByteBuffer import 数据传输 writeBuffer soc


java中nio的ScoktChannel数据传输

1.服务端server

package com.netty.redis.zookeeper.netty.unit1.oneday;

import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * @Description: ScoktChannelServer服务端
 * @ClassName: ScoktChannelServer
 * @Author zhaomx
 * @Version 1.0
 * @Date 2021-07-12 17:31
 */
@Slf4j
public class ScoktChannelServer {

    public static void main(String[] args) throws IOException {
        socketChannelServer();
    }

    public static void socketChannelServer() throws IOException {
        //1.创建一个ServerSocketChannel对象,使用open方法打开套接字通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //2.绑定host和端口
        serverSocketChannel.socket().bind(new InetSocketAddress("localhost", 4444));
        //3.通过ServerScoketChannel的accept方法生成ScoketChannel用户对象,从客户端读/写数据
        SocketChannel socketChannel = serverSocketChannel.accept();
        //4.创建写数据的缓存区对象
        ByteBuffer writeBuffer = ByteBuffer.allocate(128);
        writeBuffer.put("hello client this is from server -_-".getBytes("UTF-8"));
        //4.1把读取的数据写入到输出通道中,相当于从缓冲区中读取数据,将writeBuffer从写模式变为读模式
        //把limit设置为当前的position值,2. 把position设置为0
        writeBuffer.flip();
        socketChannel.write(writeBuffer);

        //5.创建读数据的缓存区对象
        ByteBuffer readBuffer = ByteBuffer.allocate(128);
        socketChannel.read(readBuffer);
        //5.1把读取的数据写入到输出通道中,相当于从缓冲区中读取数据,将writeBuffer从写模式变为读模式
        readBuffer.flip();

        StringBuilder stringBuilder = new StringBuilder();
        while (readBuffer.hasRemaining()) {
            stringBuilder.append((char) readBuffer.get());
        }
        log.info("从客户端接受:{}", stringBuilder.toString());
        socketChannel.close();
        serverSocketChannel.close();
    }

    public void old(){
        try {
            //1.通过ServerSocketChannel 的open()方法创建一个ServerSocketChannel对象,open方法的作用:打开套接字通道
            ServerSocketChannel ssc = ServerSocketChannel.open();
            //2.通过ServerSocketChannel绑定ip地址和port(端口号)
            ssc.socket().bind(new InetSocketAddress("127.0.0.1", 3333));
            //通过ServerSocketChannelImpl的accept()方法创建一个SocketChannel对象用户从客户端读/写数据
            SocketChannel socketChannel = ssc.accept();
            //3.创建写数据的缓存区对象
            ByteBuffer writeBuffer = ByteBuffer.allocate(128);
            writeBuffer.put("hello WebClient this is from WebServer".getBytes());
            writeBuffer.flip();
            socketChannel.write(writeBuffer);
            //创建读数据的缓存区对象
            ByteBuffer readBuffer = ByteBuffer.allocate(128);
            //读取缓存区数据
            socketChannel.read(readBuffer);
            StringBuilder stringBuffer = new StringBuilder();
            //4.将Buffer从写模式变为可读模式
            readBuffer.flip();
            while (readBuffer.hasRemaining()) {
                stringBuffer.append((char) readBuffer.get());
            }
            System.out.println("从客户端接收到的数据:" + stringBuffer);
            socketChannel.close();
            ssc.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

2.客户端client

package com.netty.redis.zookeeper.netty.unit1.oneday;

import lombok.extern.slf4j.Slf4j;

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

/**
 * @Description: 使用 SocketChannel 传输文件
 * 非阻塞客户端在发起连接后,需要不断的自旋,检测连接是否完成的。
 * SocketChannel 传输通道的 read 读取方法、write 写入方法。
 * 在 SocketChannel 传输通道关闭前,尽量发送一个输出结束标志到对方端。
 * @ClassName: ScoktChannel
 * @Author zhaomx
 * @Version 1.0
 * @Date 2021-07-12 17:24
 */
@Slf4j
public class ScoktChannelClient {

    public static void main(String[] args) throws IOException {
        //1.通过SocketChannel的open()方法创建一个SocketChannel对象
        SocketChannel socketChannel = SocketChannel.open();
        //2.连接到远程服务器(连接此通道的socket)
        socketChannel.connect(new InetSocketAddress("localhost", 4444));
        // 3.创建写数据缓存区对象
        ByteBuffer writeBuffer = ByteBuffer.allocate(128);
        writeBuffer.put("hello WebServer this is from WebClient -_-".getBytes("UTF-8"));
        writeBuffer.flip();
        socketChannel.write(writeBuffer);
        //创建读数据缓存区对象
        ByteBuffer readBuffer = ByteBuffer.allocate(128);
        socketChannel.read(readBuffer);
        //String 字符串常量,不可变;StringBuffer 字符串变量(线程安全),可变;StringBuilder 字符串变量(非线程安全),可变
        StringBuilder stringBuffer = new StringBuilder();
        //4.将Buffer从写模式变为可读模式
        readBuffer.flip();
        while (readBuffer.hasRemaining()) {
            stringBuffer.append((char) readBuffer.get());
        }
        System.out.println("从服务端接收到的数据:" + stringBuffer);

        socketChannel.close();
    }
}

标签:nio,SocketChannel,readBuffer,ScoktChannel,ByteBuffer,import,数据传输,writeBuffer,soc
来源: https://blog.csdn.net/star_pluss/article/details/118694150

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

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

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

ICode9版权所有