一些模板代码

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


相关推荐

  • docker下载安装教程_安卓安装docker

    docker下载安装教程_安卓安装docker前言Docker提供轻量的虚拟化,你能够从Docker获得一个额外抽象层,你能够在单台机器上运行多个Docker微容器,而每个微容器里都有一个微服务或独立应用,例如你可以将Tomcat运行在一个D

    2022年7月28日
    10
  • C#下使用XmlDocument详解

    C#下使用XmlDocument详解XML在开发中作为文件存储格式、数据交换的协议用的非常普遍,各个编程语言有都支持。W3C也制定了XMLDOM的标准。在这里主要介绍下.Net中的XmlDocument,包括xml读取和写入等功能。一、Xml的加载读取1、数据等准备Xml测试数据:-读取的数据,我们定义了一个实体类LocationCamera,用来保存Xml解析后的数据:public

    2022年6月22日
    164
  • postman汉化包_python模拟post请求

    postman汉化包_python模拟post请求Postman安装(汉化Postman)一、下载Postman下载地址:https://www.postman.com/downloads/二、下载汉化包下载地址:https://github.com/hlmd/Postman-cn/releases注意:中文包的版本和postman的版本一定要一致,否则会出现汉化后打不开postman的情况postman设置里能看到版本号:汉化包下对应的就可以:三、解压到对应目录四、重启P…

    2022年9月30日
    3
  • adb命令大全介绍

    adb命令大全介绍adb是什么adb的全称为AndroidDebugBridge,就是起到调试桥的作用。它就是一个命令行窗口,用于通过电脑端与模拟器或者是设备之间的交互。adb有什么用借助adb工具,我们可以

    2022年6月30日
    27
  • 关于我妈的一切_networkmanager是什么服务

    关于我妈的一切_networkmanager是什么服务NetworkManager(NetworManager)是检测网络、自动连接网络的程序。无论是无线还是有线连接,它都可以令您轻松管理。对于无线网络,网络管理器可以自动切换到最可靠的无线网络。利用网络管理器的程序可以自由切换在线和离线模式。网络管理器可以优先选择有线网络,支持VPN。网络管理器最初由Redhat公司开发,现在由GNOME管理。1.查看NetworkManager…

    2022年10月4日
    2
  • 基于SQL的日志分析工具myselect

    基于SQL的日志分析工具myselect

    2021年11月29日
    38

发表回复

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

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