Java NIO 同步非阻塞Socket DEMO

在这个例子上做的修改:http://blog.csdn.net/eclipser1987/article/details/7329362

Server.java

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.Iterator;

/**
 * Created by yangankang on 16/2/20.
 */
public class Server implements Runnable {

    private int port = 8888;
    private ServerSocketChannel socketChannel;
    private SocketChannel clientChannel;
    private Selector selector;
    private ByteBuffer byteBuffer = ByteBuffer.allocate(512);

    public Server() {
        init();
    }

    public void init() {
        try {
            this.selector = SelectorProvider.provider().openSelector();
            this.socketChannel = ServerSocketChannel.open();
            this.socketChannel.configureBlocking(false);
            this.socketChannel.socket().bind(new InetSocketAddress("localhost", port));
            this.socketChannel.register(this.selector, SelectionKey.OP_ACCEPT);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        Server server = new Server();
        Thread thread = new Thread(server);
        thread.start();
    }

    @Override
    public void run() {
        while (true) {
            try {
                System.err.println("Server Start.");
                this.selector.select();
                Iterator iterator = this.selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = (SelectionKey) iterator.next();
                    iterator.remove();
                    if (!key.isValid()) {
                        continue;
                    }
                    if (key.isAcceptable()) {
                        this.accept(key);
                    } else if (key.isReadable()) {
                        this.read(key);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void accept(SelectionKey key) {
        ServerSocketChannel socketChannel = (ServerSocketChannel) key.channel();
        try {
            clientChannel = socketChannel.accept();
            clientChannel.configureBlocking(false);
            clientChannel.register(this.selector, SelectionKey.OP_READ);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void read(SelectionKey key) {
        this.byteBuffer.clear();
        SocketChannel socketChannel = (SocketChannel) key.channel();
        try {
            int count = socketChannel.read(this.byteBuffer);
            if (count == -1) {
                key.channel().close();
                key.channel();
                return;
            }
            String string = new String(this.byteBuffer.array()).trim();
            System.out.println("from client message:" + string);
            socketChannel.write(ByteBuffer.wrap(("you say:" + string).getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Client.java

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * Created by yangankang on 16/2/21.
 */
public class Client {

    private ByteBuffer buffer = ByteBuffer.allocate(512);
    private String url = "localhost";
    private int port = 8888;

    public void send() {
        InetSocketAddress address = new InetSocketAddress(url, port);

        SocketChannel socketChannel = null;
        while (true) {
            byte[] b = new byte[512];
            try {
                System.err.print("input your message:");
                System.in.read(b);
                socketChannel = SocketChannel.open();
                socketChannel.connect(address);
                buffer.clear();
                buffer.put(b);
                buffer.flip();
                socketChannel.write(buffer);
                buffer.clear();
                socketChannel.configureBlocking(true);
                ByteBuffer readBuffer = ByteBuffer.allocate(512);
                socketChannel.read(readBuffer);
                System.out.println("from client message:" + (new String(readBuffer.array()).trim()));
                socketChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (socketChannel != null)
                    try {
                        socketChannel.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
        }
    }

    public static void main(String args[]) {
        Client client = new Client();
        client.send();
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值