一些模板代码

一些模板代码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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 太原智慧小区有哪些_智慧城市规划

    太原智慧小区有哪些_智慧城市规划经过3个月的紧张施工,至7月初,位于龙城大街的“首开·国风上观”小区成为我市首个实现电、水、热采集“多表合一”的智能化小区。记者从国网太原供电公司了解到,该试点小区住户达3524户,是目前国内“多表合一”改造试点中规模较大的,也是我省试点中规模最大的小区。今年,国家发改委、国家能源局、工信部曾联合出台《关于推进“互联网+”智慧能源发展的指导意见》,其中…

    2022年10月9日
    4
  • 雷军反击董明珠:感觉董总好像认输了似的

    雷军反击董明珠:感觉董总好像认输了似的

    2022年2月5日
    46
  • 【题解】递归数列

    【题解】递归数列"题目链接"题目大意:给定序列迭代规则,求一段的序列和。特点是要求的序列很长。Solution观察到,由于是求和,我们可以想到前缀和的思想。也就是说,对于求$\sum_{i=

    2022年7月2日
    31
  • 有哪些免费的方法能将PDF导出成JPG图片?

    有哪些免费的方法能将PDF导出成JPG图片?根据不同的应用场合,有时需要将PDF文件导出成图片使用,有哪些能够免费将PDF转成JPG的方法呢?下面分享两种方法你一定用的上。方式一:在线转换首先打开百度或其他搜索器输入speedpdf进行搜索,然后打开这款在线转换工具,接着选择首页中的PDFtoJPG;(网页可以翻译成中文)第二步:然后根据上传文件页面的提示选择需要转换的PDF文件,可以批量选择多个文档上传;第三步:点击文档后的convert按钮即可开始转换,转换完成后点击下载即可。(下载后是一个压缩包解压即可)方式二:编辑器导出

    2022年5月15日
    39
  • ASP.NET MVC使用javascript

    ASP.NET MVC使用javascript在母版页,也就是布局页,使用@if(IsSectionDefined(“SubMenu”)){@RenderSection(“SubMenu”,required:false)}SubMenu:这个名字随便取在需要用脚本的地方@sectionSubMenu{<scriptsrc=”~/js/submenu.js”></script>}就完成了。…

    2022年7月22日
    9
  • 国外全能免费主页空间

    国外全能免费主页空间国外全能免费主页空间,支持ASP.NET、PHP、CGI等 [来源:不详|作者:佚名|时间:2007-6-622:19:28|收藏本文]   WebHostforASP.NET提供15M免费主页空间,每月2G的流量限制,web方式上传管理文件,支持ASP、ASP.NET、PHP、Perl、CGI以及Access数据库,无广告。必须拥有顶级域名才能申请,如果您手头上有空

    2022年7月11日
    25

发表回复

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

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