zoukankan      html  css  js  c++  java
  • 一些模板代码

    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();
                }
            }
        }
    }
    
    
  • 相关阅读:
    存储器多级结构
    649. Dota2 参议院
    pycharm安装第三方库失败
    python -m pip install --upgrade pip升级失败
    P1149 火柴棒等式
    HTTP详解
    ref与out
    EF查询数据库框架的搭建
    EF查询数据库框架的搭建
    css清除浮动
  • 原文地址:https://www.cnblogs.com/zhouyu0-0/p/13872933.html
Copyright © 2011-2022 走看看