java 纯nio使用 serverSocketChannel与socketChannel 最简单的例子,没有使用select,多线程等等

serverSocketChannel 是服务器端,监听端口,等待链接

运行main后,浏览器访问:http://localhost:8080/

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class Server {

    public static void main(String[] args) throws Exception {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(8080));

        while(true){
            SocketChannel socketChannel = serverSocketChannel.accept();
            System.out.println(socketChannel);
            System.out.println("conn.........."+socketChannel.getRemoteAddress().toString());

            ByteBuffer buf = ByteBuffer.allocate(128);
            buf.clear();
            int len = socketChannel.read(buf);
            int count=0;
            while (len>0)
            {
                count +=len;
                buf.flip();
                while (buf.position()<buf.limit())
                {
                    System.out.print((char)buf.get());
                }
                //#todo 未读满缓存,不一定读完了
                if(buf.limit()<buf.capacity())
                {
                    break;
                }
//                System.out.println("next read.................");
                buf.clear();
                len = socketChannel.read(buf);
            }
            System.out.println("has buf"+count+" ..............");
            buf.clear();

            System.out.println("output");

            StringBuilder sendStr = new StringBuilder();
            sendStr.append("Http/1.1 200 Ok\r\n");
            sendStr.append("Content-Type:text/html;charset=UTF-8\r\n");
            sendStr.append("\r\n");
            sendStr.append("<html><head><title>显示报文</title></head><body>hi,world</body></html>");

            buf=ByteBuffer.wrap(sendStr.toString().getBytes("UTF-8"));
            socketChannel.write(buf);
            socketChannel.close();
        }
    }

}

socketChannel是连接服务使用,可以访问web服务器或做proxy代理服务

启动main后,控制台打印得到的http信息,现在很多都启用了全站https,所以很多都是返回302

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class Client {

    public static void main(String[] args) throws Exception {
//        String url = "ifeve.com";
//        String url = "www.baidu.com";
//        String url = "blog.csdn.net";
        String url = "github.com";


        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress(url, 80));
        System.out.println("conn..............");

        while (true) {
            System.out.println("whild.................");
            if (socketChannel.isConnected()) {
                System.out.println("pending.....................");
                //发送http
                StringBuilder sendStr = new StringBuilder();
                sendStr.append("GET / HTTP/1.1\r\n");
                sendStr.append("Host: "+url+"\r\n");
                //gzip压缩
//                sendStr.append("Accept-Encoding: gzip, deflate, br\r\n");
                //http协议,需要空一行
                sendStr.append("\r\n");

                ByteBuffer buf = ByteBuffer.wrap(sendStr.toString().getBytes("UTF-8"));
                int bytesWrite = socketChannel.write(buf);
                System.out.println(bytesWrite);
                buf.clear();

                int read = 0;
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                while ((read = socketChannel.read(buffer)) != -1) {
                    {
                        System.out.println("read " + read + ".....................");
                        buffer.flip();
                        while (buffer.position() < buffer.limit()) {
                            //不能解析中文
//                            System.out.print((char) buffer.get());
                            //解析中文,不知道是否有个别乱码,缓存刚好截断utf8中文(三个字节)?
                            System.out.println(Charset.forName("UTF-8").newDecoder().decode(buffer).toString());
                        }
                        //#todo 需要计算body长度,缓存没满不一定读完数据,html文档没读完
                        if (buffer.limit() < buffer.capacity()) {
                            break;
                        }
                        buffer.clear();
                    }
                }
            }
            socketChannel.close();
            break;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/c5113620/article/details/80377009
今日推荐