1. 程式人生 > >不用netty實現OIO和NIO連線通訊

不用netty實現OIO和NIO連線通訊

首先是 OIO server端的

package com.fk.testIO;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;

/**
 * Created by fengkai on 11/04/17.
 */
public class OIO {

    public void serve(int port) throws
IOException{ //繫結埠 final ServerSocket socket = new ServerSocket(port); for(;;){ final Socket clientSocket = socket.accept(); System.out.println("A connetction from " +clientSocket); new Thread(new Runnable() { @Override public
void run() { OutputStream out; InputStream in; try{ in = clientSocket.getInputStream(); byte[] bytes = new byte[1024]; int bytelen = 0; int bytein = 0
; StringBuffer sb = new StringBuffer(); while ((bytelen = in.read(bytes)) != -1){ String str = new String(bytes, bytein, bytelen); sb.append(str); } System.out.println(sb.toString()); out = clientSocket.getOutputStream(); out.write("HelloWorld".getBytes(Charset.forName("UTF-8"))); out.flush(); clientSocket.close(); }catch (IOException e){ e.printStackTrace(); } } }).start(); } } public static void main(String[] args) { final int port = 8888; new Thread(new Runnable() { @Override public void run() { try { new OIO().serve(port); } catch (IOException e) { e.printStackTrace(); } } }).start(); } }

接下來是NIO 的server

package com.fk.testIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
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.util.Iterator;
import java.util.Set;

/**
 * Created by fengkai on 11/04/17.
 */
public class NIO {

    public void service(int port) throws IOException{
        // 開啟selector 處理channel
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        ServerSocket socket = serverChannel.socket();
        InetSocketAddress adress = new InetSocketAddress(port);
        socket.bind(adress);
        Selector selector = Selector.open();
        //註冊selector
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
        final ByteBuffer msg = ByteBuffer.wrap("hello".getBytes());
        for(;;){
            //等待新的處理事件
            try {
                selector.select();
            } catch (IOException e) {
                e.printStackTrace();
                break;
            }
            //所有的selectionKey例項
            Set<SelectionKey> readKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = readKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                iterator.remove();;
                //檢視它是否是等待接受的新連線

                try {
                    if(key.isAcceptable()){
                        ServerSocketChannel server = (ServerSocketChannel) key.channel();
                        SocketChannel client = server.accept();
                        client.configureBlocking(false);
                        client.register(selector, SelectionKey.OP_WRITE|SelectionKey.OP_READ, msg.duplicate());
                        System.out.println("a new Connetion" + client);
                    }
                    //準備好寫
                    if(key.isWritable()){
                        SocketChannel client = (SocketChannel) key.channel();
                        ByteBuffer buffer = (ByteBuffer) key.attachment();
                        while (buffer.hasRemaining()){
                            if(client.write(buffer) == 0){
                                break;
                            }
                        }
                        client.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    key.cancel();
                    try {
                        key.channel().close();
                    }catch (IOException cex){
                        cex.printStackTrace();
                    }
                }


            }

        }


    }

}