一些模板代码

一些模板代码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)
上一篇 2022年7月3日 下午4:36
下一篇 2022年7月3日 下午4:36


相关推荐

  • 【深度学习】梯度下降算法和随机梯度下降算法「建议收藏」

    【深度学习】梯度下降算法和随机梯度下降算法「建议收藏」导语梯度是神经网络中最为核心的概念,在介绍梯度之前我们要先知道数学中的导数以及偏微分的理论概念。导数这里套用维基百科上的介绍,导数描述了函数在某一点附件的变化率,导数的本质是通过极限对函数进行局部的线性逼近,当函数\(f\)的自变量在一点\(x_0\)上产生一个增量\(△x\)时,则函数值的增量\(△y\)与自变量的增量\(△x\)的比值在\(△x\)趋于0时的极限存在,即为\(f\)在\(…

    2025年9月3日
    6
  • 大数据面试求职经验总结

    大数据面试求职经验总结计算机专业面试求职篇 大数据岗为例 包括面试经验分享 简历制作 经验及心得分享等 写在前面 空杯心态 把握好校招机会 它是你最容易通往大厂的机会

    2026年3月16日
    2
  • Throw和Throws的区别

    Throw和Throws的区别Throw 作用在方法内 表示抛出具体异常 由方法体内的语句处理 具体向外抛出的动作 所以它抛出的是一个异常实体类 若执行了 Throw 一定是抛出了某种异常 Throws 作用在方法的声明上 表示如果抛出异常 则由该方法的调用者来进行异常处理 主要的声明这个方法会抛出会抛出某种类型的异常 让它的使用者知道捕获异常的类型 出现异常是一种可能性 但不一定会发生异常 实例 vo

    2026年3月19日
    2
  • AOP AspectJ Pointcuts 表达式 语法 示例

    AOP AspectJ Pointcuts 表达式 语法 示例

    2021年5月27日
    104
  • 马斯克密集点赞中国AI:Kimi、字节、Qwen齐获顶流认可

    马斯克密集点赞中国AI:Kimi、字节、Qwen齐获顶流认可

    2026年3月18日
    2
  • i am running什么意思_hirunning

    i am running什么意思_hirunningnmtui提示:NetworkManagerisnotrunning.启动:sudoservicenetwork-managerstart提示:Redirectingto/bin/systemctlstartnetwork-manager.serviceFailedtostartnetwork-manager.service:Unitnotfound.安装:yuminstallNetworkManager-tui…

    2026年4月17日
    3

发表回复

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

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