码迷,mamicode.com
首页 > 编程语言 > 详细

java NIO入门【原】

时间:2017-07-31 18:47:25      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:关闭   har   net   config   localhost   服务端   package   通道   log   

server

package com.server;

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 {
        //新建TCP服务端
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //绑定TCP端口
        serverSocketChannel.socket().bind(new InetSocketAddress(9999));
        //配置成"非阻塞"
        serverSocketChannel.configureBlocking(false);
        while (true) {
            //允许接收TCP链接
            SocketChannel socketChannel = serverSocketChannel.accept();
            //当有TCP连接上来时,获取到的就不为空
            if (socketChannel != null) {
                //写英文数据"生命不步,战斗不息"
                String newData = System.currentTimeMillis() + ": Cease to struggle and you cease to live .";
                //开辟缓存
                ByteBuffer buf = ByteBuffer.allocate(1024);
                //重置,准备写入数据到缓存
                buf.clear();
                //真正写入数据到缓存
                buf.put(newData.getBytes());
                //准备从缓存读取数据
                buf.flip();
                //如果读到数据有剩余
                while (buf.hasRemaining()) {
                    //真正从缓存读取数据,并写入到通道中
                    socketChannel.write(buf);
                }
            }
        }
    }
}

 

 

client

package com.client;

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

public class client {
    public static void main(String[] args) throws Exception {
        //新建TCP服务端
        SocketChannel socketChannel = SocketChannel.open();
        //链接到本地的8888端口
        socketChannel.connect(new InetSocketAddress("localhost", 8888));
        //开辟缓存
        ByteBuffer buf = ByteBuffer.allocate(1024);
        //重置,准备写入数据到缓存
        buf.clear();
        //真正从通道读取数据到缓存
        int bytesRead = socketChannel.read(buf);
        //准备从缓存读取数据
        buf.flip();
        //如果读到数据有剩余
        while (buf.hasRemaining()) {
            //取一个字节
            byte b = (byte) (buf.get());
            //转成一个字符
            System.out.print((char) b);
        }
        //关闭通道
        socketChannel.close();
    }
}

 

java NIO入门【原】

标签:关闭   har   net   config   localhost   服务端   package   通道   log   

原文地址:http://www.cnblogs.com/whatlonelytear/p/7264382.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!