一些模板代码

一些模板代码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();
            }
        }
    }
}

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

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

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • ov7740摄像头_雷威视监控摄像头二码是无

    ov7740摄像头_雷威视监控摄像头二码是无近日入手了一块正点原子家的OV7725摄像头模块,秉着小白尽可能学得透彻些的想法,选择了野火家的相同摄像头教学视频。链接如下:【单片机】野火STM32F103教学视频(配套霸道/指南者/MINI)【全】(刘火良老师出品)(无字幕)_哔哩哔哩_bilibili现对PPT和火哥所授内容进行整理:在各类传感器获取信息中,图像包含有最丰富的信息。但是摄像头模块仅用于获取输出图像,像利用摄像头进行人脸识别,图像识别之类功能,主要是依赖于识别算法,这是另外的技术。分类:摄像头按输出信号分类可分为模拟

    2022年9月23日
    0
  • 你用对锁了吗?浅谈 Java “锁” 事

    你用对锁了吗?浅谈 Java “锁” 事

    2020年11月20日
    181
  • 关于Java中length、length()、size()的区别

    关于Java中length、length()、size()的区别首先区分一下length和length();length不是方法,是属性,数组的属性;public static void main(String[] args) { int[] intArray = {1,2,3}; System.out.println("这个数组的长度为:" + intArray.length);}length()是字符串String的一个方法;p…

    2022年6月13日
    34
  • 索引初探(二)

    索引初探(二)

    2021年11月25日
    47
  • 微商分销代理商城源码-代理等级和升级条件

    微商分销代理商城源码-代理等级和升级条件介绍:微商分销代理商城源码基于think框架开发是一款微商分销代理商城源码,可以自己设置代理等级和升级条件(如购买指定商品、消费额度)网站搭建方式介绍:测试环境php7.0+mysql5.6数据库配置文件\application\database.php后台/admin用户:admin密码:123456网盘下载地址:http://kekewl.cc/jpaQnrd7VcZ0图片:网站源码首页截图演示网站后台截图演示…

    2022年5月13日
    39
  • Android百度地图获取开发版SHA1值和发布版SHA1值

    Android百度地图获取开发版SHA1值和发布版SHA1值开发版SHA1获取:首先找到C:\Users****.android文件夹,在.android文件下打开当前文件夹的控制台,输入keytool-v-list-keystoredebug.keystore即可,遇到输入口令,一般默认为android,如图:发布版SHA1获取:首先创建该项目,并打开AndroidStudio选中Build->GenerateS…

    2022年8月10日
    4

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

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