一些模板代码

一些模板代码jdbc模板代码nio读写模板代码publicclassNewBufferTest{publicstaticvoidmain(String[]args)throwsIOExce

大家好,又见面了,我是你们的朋友全栈君。

jdbc模板代码

nio读写模板代码

public class NewBufferTest {
    public static void main(String[] args) throws IOException {
        ReadableByteChannel src = Channels.newChannel(System.in);
        Path p = Paths.get("./output2");
        File output1 = Files.createFile(p).toFile();
        WritableByteChannel des = new FileOutputStream(output1).getChannel();
        copyBuffer1(src,des);
    }

    private static void copyBuffer1(ReadableByteChannel src, WritableByteChannel des) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(1024 * 16);
        while(src.read(buffer)!=-1){
            //准备写入
            buffer.flip();
            //缓存数据写入
            des.write(buffer);
            //压缩
            buffer.compact();
        }
        //如果读完后buffer内还有剩余
        buffer.flip();
        while(buffer.hasRemaining()) des.write(buffer);

    }

    private static void copyBuffer2(ReadableByteChannel src,WritableByteChannel des)throws IOException{
        ByteBuffer buffer = ByteBuffer.allocate(1024 * 16);
        //保证读之前 buffer清空
        while(src.read(buffer)!=-1){
            buffer.flip();
            while(buffer.hasRemaining())des.write(buffer);
            buffer.clear();
        }
    }
}

Channel 相关代码

# 时间客户端
package pers.yuriy.demo.nio.socketChannels;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.DatagramChannel;
import java.util.*;

public class TimeClient {
    private static final int DEFAULT_TIME_PORT=37;
    private  static final long DIFF_1900 =220898800L;
    protected  int port =DEFAULT_TIME_PORT;
    protected List remoteHosts;
    protected DatagramChannel channel;
    
    public TimeClient(String[] argv)throws Exception{
        if(argv.length==0){
            throw new Exception("Usage:[ -p port] host ...");
        }
        parseArgs(argv);
        this.channel = DatagramChannel.open();
    }
    
    protected InetSocketAddress receivePacket(DatagramChannel channel, ByteBuffer buffer) throws Exception{
        buffer.clear();
        return ((InetSocketAddress)channel.receive(buffer));
    }
    
    protected void sendRequests() throws Exception{
        ByteBuffer buffer = ByteBuffer.allocate(1);
        Iterator it = remoteHosts.iterator();
        while(it.hasNext()){
            InetSocketAddress sa = (InetSocketAddress) it.next();
            System.out.println("Request time from "+ sa.getHostName() +":"+sa.getPort());
            buffer.clear().flip();
            channel.send(buffer,sa);
        }
    }
    
    public void getReplies() throws Exception{
        ByteBuffer longBuffer = ByteBuffer.allocate(8);
        longBuffer.order(ByteOrder.BIG_ENDIAN);
        longBuffer.putLong(0,0);
        longBuffer.position(0);
        ByteBuffer buffer = longBuffer.slice();
        int expect = remoteHosts.size();
        int replies = 0;

        System.out.println("");
        System.out.println("Waiting for replies...");
        
        while(true){
            InetSocketAddress sa;
            sa = receivePacket(channel,buffer);
            buffer.flip();
            replies++;
            printTime(longBuffer.getLong(0),sa);
            if(replies == expect){
                System.out.println("All packets answered");
                break;
            }
            System.out.println("Received "+replies+" of "+ expect + " replies");
        }
    }
    
    protected void printTime(long remote1900,InetSocketAddress sa){
        long local = System.currentTimeMillis()/1000;
        long remote = remote1900 -DIFF_1900;
        Date remoteDate = new Date(remote*1000);
        Date localDate = new Date(local*1000);
        long skew = remote - local;
        System.out.println( " Reply form "+sa.getHostName() +":"+sa.getPort());
        System.out.println(" there: "+ remoteDate);
        System.out.println(" this: "+ localDate);
        if(skew == 0){
            System.out.println("none");
        }
        else if(skew >0){
            System.out.println( skew + "seconds ahead");
        }
        else{
            System.out.println( -skew +" seconds behind");
        }
    }
    
    protected void parseArgs(String[] argv){
        remoteHosts = new LinkedList();
        for(int i=0;i<argv.length;i++){
            String arg = argv[i];
            if(arg.equals("-p")){
                i++;
                this.port = Integer.parseInt(argv[i]);
                continue;
            }
            InetSocketAddress sa = new InetSocketAddress(arg,port);
            if(sa.getAddress()==null){
                System.out.println("Cannot resolve address "+ arg);
                continue;
            }
            remoteHosts.add(sa);
        }
    }

    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(System.in);
        String[] argv = in.nextLine().split(" ");
        TimeClient client = new TimeClient(argv);
        client.sendRequests();
        client.getReplies();
    }
}

# 时间服务器
package pers.yuriy.demo.nio.socketChannels;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.DatagramChannel;

public class TimeServer {
    private static final int DEFAULT_TIME_PORT = 37;
    private static final long DIFF_1900 = 220898800L;
    protected DatagramChannel channel;

    public TimeServer(int port) throws Exception {
        this.channel = DatagramChannel.open();
        this.channel.socket().bind(new InetSocketAddress(port));
        System.out.println("Listening on port " + port + " for time requests");
    }

    public void listen() throws Exception {
        ByteBuffer longBuffer = ByteBuffer.allocate(8);

        longBuffer.order(ByteOrder.BIG_ENDIAN);

        longBuffer.putLong(0, 0);

        longBuffer.position(4);

        ByteBuffer buffer = longBuffer.slice();

        while (true) {
            buffer.clear();
            SocketAddress sa = this.channel.receive(buffer);
            if (sa == null) {
                continue;
            }
            System.out.println(" Time request from " + sa);
            buffer.clear();
            longBuffer.putLong(0, (System.currentTimeMillis() / 1000));
            this.channel.send(buffer, sa);
        }
    }

    public static void main(String[] args) {
        int port = DEFAULT_TIME_PORT;
        if(args.length>0){
            port = Integer.parseInt(args[0]);
        }
        try {
            TimeServer server = new TimeServer(port);
            server.listen();
        } catch (Exception e) {
            System.out.println("Cant bind to the port "+ port +", try a different one");
        }
    }
}

#selector使用
package pers.yuriy.demo.nio.SelectorsTest;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class SelectSockets {
    public static int PORT_NUMBER = 1234;

    public void go(String[] argv) throws Exception {
        int port = PORT_NUMBER;
        if (argv.length > 0) {
            port = Integer.parseInt(argv[0]);
        }
        System.out.println("Listening on port:" + port);

        ServerSocketChannel serverChannel = ServerSocketChannel.open();

        ServerSocket serverSocket = serverChannel.socket();

        Selector selector = Selector.open();

        serverSocket.bind(new InetSocketAddress(port));

        serverChannel.configureBlocking(false);

        serverChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            int n = selector.select();
            if (n == 0) {
                continue;
            }
            Iterator it = selector.selectedKeys().iterator();
            while (it.hasNext()) {
                SelectionKey key = (SelectionKey) it.next();

                if (key.isAcceptable()) {
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    SocketChannel channel = server.accept();

                    registerChannel(selector, channel, SelectionKey.OP_READ);

                    sayHello(channel);
                }

                if (key.isReadable()) {
                    readDataFromSocket(key);
                }
                it.remove();
            }
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/155628.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • Python爬取美女图片 爬虫基础

    Python爬取美女图片 爬虫基础Python爬取美女图片爬虫基础简述实现思路关键代码文件下载爬虫代码成果简述作为一个考研狗,每天除了日复一日的复习外,偶尔也想给自己寻找一些生活的小乐趣,今天突然想到了自己曾经稍微接触的爬虫,想看看可以爬取些图片放到电脑上,就花了些时间改了改之前的爬虫代码,爬取了一部分照片先量一下战绩吧。照片不多但也算是自己的一次爬虫小经验。实现思路爬虫的网页很简单,照片真实路径都在页面中直接可以拿到主要流程就是先进入照片浏览的主页,每个照片的主页都会链接几个照片页面,像下面这样,每个图片都会链接一个网页

  • c++ stl容器_c++ std是什么

    c++ stl容器_c++ std是什么文章目录C++中常用的std标准容器顺序容器:有序关联容器:无序关联容器:顺序容器1. vector容器a. vector的定义与初始化b. vecotr常使用的操作c. 小结:2. string容器a. string的初始化b. string中包含的专有的操作(相对于vector来说)c字符串的转换函数d 对字符的操作(在cctype头文件中,并不属于string头文件的范围,但是关系很紧密的)…

  • java面试题csdn_java底层面试题

    java面试题csdn_java底层面试题问题是:n只奶牛坐在一排,每个奶牛拥有ai个苹果,现在你要在它们之间转移苹果,使得最后所有奶牛拥有的苹果数都相同,每一次,你只能从一只奶牛身上拿走恰好两个苹果到另一个奶牛上,问最少需要移动多少次可以平分苹果,如果方案不存在输出-1输出描述:输出一行表示最少需要移动多少次可以平分苹果,如果方案不存在则输出-1。输入例子:471595输出例子:3im…

  • 初学css list-style属性「建议收藏」

    初学css list-style属性「建议收藏」网上很多css布局中会看到这样的一句:list-style:none;那么list-style到底什么意思?中文即:列表样式:无;其实它是一个简写属性,包含了所有列表属性,具体包含list-sty

  • SLAM技术概述_SRAM工艺

    SLAM技术概述_SRAM工艺导语随着最近几年机器人、无人机、无人驾驶、VR/AR的火爆,SLAM技术也为大家熟知,被认为是这些领域的关键技术之一。本文对SLAM技术及其发展进行简要介绍,分析视觉SLAM系统的关键问题以及在实际应用中的难点,并对SLAM的未来进行展望。1.SLAM技术SLAM(SimultaneousLocalizationandMapping),同步定位与地图构建,最早在机器人领域提出,…

  • Pytorch(五)入门:DataLoader 和 Dataset

    Pytorch(五)入门:DataLoader 和 DatasetDataLoader和Dataset构建模型的基本方法,我们了解了。接下来,我们就要弄明白怎么对数据进行预处理,然后加载数据,我们以前手动加载数据的方式,在数据量小的时候,并没有太大问题,但是到了大数据量,我们需要使用shuffle,分割成mini-batch等操作的时候,我们可以使用PyTorch的API快速地完成这些操作。Dataset是一个包装类,用来将数据包装为Datas…

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号