simple example for nio

Server

package myserver.net;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
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;

public class Server extends Thread
{
    Selector selector;

    ServerSocketChannel serverSocket;
    
    public static void main(String args[])
    {
        try
        {
            Server s=new Server(5001);
            s.start();
        } 
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public Server(int port) throws Exception
    {
        ServerSocketChannel sc = ServerSocketChannel.open();
        sc.socket().bind(new InetSocketAddress(port));
        sc.configureBlocking(false);
        selector= Selector.open();
        SelectionKey sk = sc.register(selector, SelectionKey.OP_ACCEPT);
    }

    public void run()
    {
        try
        {
            while (!Thread.interrupted())
            {
                selector.select();
                Set selected = selector.selectedKeys();
                Iterator it = selected.iterator();
                while (it.hasNext())
                {
                    SelectionKey key = (SelectionKey) it.next();

                    if (key.isValid() == false)
                    {
                        continue;
                    }
                    
                    if (key.isAcceptable())
                    {
                        doAccept(key);
                    } 
                    else if (key.isReadable())
                    {
                        doRead(key);
                    }
                }
                selected.clear();
            }
        } 
        catch (Exception e)
        {
           e.printStackTrace();
        }
    }

    private void doAccept(SelectionKey sk)
    {
        try
        {
            ServerSocketChannel ssc = (ServerSocketChannel) sk.channel();
            SocketChannel sc = ssc.accept();
            sc.configureBlocking(false);
            sc.register(selector, SelectionKey.OP_READ);
            //If you do the accept in another thread
            //you should do the following to return the  
            //select() method.
            //sel.wakeup();
        }
        catch (ClosedChannelException e)
        {
            e.printStackTrace();
        } 
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    private void doRead(SelectionKey sk)
    {
        try
        {
            SocketChannel sc = (SocketChannel) sk.channel();
            ByteBuffer bf=ByteBuffer.allocate(100);
            sc.read(bf);
            System.out.println(new String(bf.array()));
            
            String ret="hello!";            
            ByteBuffer retBf=ByteBuffer.wrap(ret.getBytes());
            sc.write(retBf);
            
            sc.close();
        } 
        catch (ClosedChannelException e)
        {
            e.printStackTrace();
        } 
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

client
package myserver.net;

import java.net.InetAddress;
import java.net.Socket;
import java.io.*;

public class Client
{
    public static void main(String[] args)
    {
        Socket client = null;
        DataOutputStream out = null;
        DataInputStream in = null;
        try
        {
            client = new Socket(InetAddress.getLocalHost(), 5001);
            client.setSoTimeout(10000);
            out = new DataOutputStream((client.getOutputStream()));

            String send = "me";
            byte[] request = send.getBytes();
            out.write(request);
            out.flush();
            client.shutdownOutput();

            in = new DataInputStream(client.getInputStream());
            byte[] reply = new byte[40];
            in.read(reply);
            System.out.println("ret: " + new String());

            in.close();
            out.close();
            client.close();
        } 
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
posted on 2006-04-05 16:41  泾溪  阅读(501)  评论(0编辑  收藏  举报