天天看点

Java IO示例代码

//BIO服务端

public class BIOServer {

public static void main(String[] args) {
    try {
        ServerSocket serverSocket = new ServerSocket();
        InetSocketAddress address = new InetSocketAddress("127.0.0.1", 9001);
        serverSocket.bind(address);
        while (true) {
            Socket socket = serverSocket.accept();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(socket.getLocalAddress().getHostAddress() + "连接了");
                    InputStream inputStream = null;
                    try {
                        inputStream = socket.getInputStream();
                        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                        BufferedReader reader = new BufferedReader(inputStreamReader);
                        String str = null;
                        str = reader.readLine();
                        System.out.println(str);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}           

}

//BIO客户端

public class BIOClient {

public static void main(String[] args) {
    try {
        Socket socket = new Socket("127.0.0.1", 9001);
        OutputStream outputStream = socket.getOutputStream();
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
        BufferedWriter writer = new BufferedWriter(outputStreamWriter);
        String str = "你好";
        writer.write(str);
        //刷新输入流
        writer.flush();
        //关闭socket的输出流
        socket.shutdownOutput();
    } catch (Exception e) {
        e.printStackTrace();
    }
}           

//NIO服务端

public class NIOServer {

/**
 * 选择器
 */
private Selector selector;

/**
 * 通道
 */
ServerSocketChannel serverSocketChannel;

public void initServer(int port) throws IOException
{
    //打开一个通道
    serverSocketChannel = ServerSocketChannel.open();

    //通道设置非阻塞
    serverSocketChannel.configureBlocking(false);

    //绑定端口号
    serverSocketChannel.socket().bind(new InetSocketAddress("0.0.0.0", port));

    //注册
    this.selector = Selector.open();
    //先注册事件
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
}

public void listen() throws IOException
{
    System.out.println("server started succeed!");

    while (true)
    {
        //阻塞到至少有一个就绪通道
        selector.select();
        Iterator<SelectionKey> ite = selector.selectedKeys().iterator();
        while (ite.hasNext())
        {
            SelectionKey key = ite.next();
            if (key.isAcceptable())
            {
                //接收新请求,并创建新通道
                SocketChannel channel = serverSocketChannel.accept();
                channel.configureBlocking(false);
                //通道注册可读事件
                channel.register(selector, SelectionKey.OP_READ);
            }
            else if (key.isReadable())
            {
                recvAndReply(key);
            }
            ite.remove();
        }
    }
}

public void recvAndReply(SelectionKey key)
{
    SocketChannel channel = (SocketChannel) key.channel();
    try {
        ByteBuffer buffer = ByteBuffer.allocate(256);
        int i = channel.read(buffer);
        if (i != -1) {
            String msg = new String(buffer.array()).trim();
            System.out.println(new Date() + ",NIO server received message =  " + msg);
            System.out.println(new Date() + ",NIO server reply =  " + msg);
            //通道写入数据
            channel.write(ByteBuffer.wrap(msg.getBytes()));
        } else {
            //多线程处理业务
            channel.close();
        }
    }catch (IOException e) {
        e.printStackTrace();
        try {
            channel.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

public static void main(String[] args) throws IOException
{
    NIOServer server = new NIOServer();
    server.initServer(8001);
    server.listen();
}           

//NIO客户端

public class NIOClient {

/**
 * 通道
 */
SocketChannel channel;

public void initClient(String host, int port) throws IOException
{
    //构造socket连接
    InetSocketAddress servAddr = new InetSocketAddress(host, port);

    //通过通道,打开连接
    this.channel = SocketChannel.open(servAddr);
}

public void sendAndRecv(String words) throws IOException {
    byte[] msg = new String(words).getBytes();
    ByteBuffer buffer = ByteBuffer.wrap(msg);
    System.out.println(new Date() + ",Client sending: " + words);
    //通道写数据
    channel.write(buffer);
    buffer.clear();
    //阻塞,通道读数据
    channel.read(buffer);
    System.out.println(new Date() + ",Client received: " + new String(buffer.array()).trim());
}

public void close() throws IOException {
    channel.close();
}

public static void main(String[] args) throws IOException {
    NIOClient client = new NIOClient();
    try {
        client.initClient("localhost", 8001);
        Random random = new Random(10000000);
        while (true) {
            client.sendAndRecv(random.nextInt() + ",I am a client");
        }
    } catch (Exception e) {
        e.printStackTrace();
        client.close();
    }
}