socket通道小例子

用这个小例子,实现客户端提交加法数据,服务端计算结果并返回给客户端。
服务端代码

package me.zhengzx.nio;

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

public class NIOChannelServer {
    private ByteBuffer buff = ByteBuffer.allocate(1024);
    //创建一个int缓冲区的视图,此缓冲区的内容的更改在新缓冲区中是可见的,反之亦然
    private IntBuffer intBuff = buff.asIntBuffer();
    private SocketChannel clientChannel = null;
    private ServerSocketChannel serverChannel = null;

    /**
     * 打开服务端的通道
     * @throws IOException
     */
    public void openChannel() throws IOException {
        //建立一个新的连接的通道
        serverChannel = ServerSocketChannel.open();
        //为新的通道设置访问的端口
        serverChannel.socket().bind(new InetSocketAddress(8888));
        System.out.println("服务端通道已经打开");
    }

    /**
     * 等待客户端的请求连接
     * @throws IOException
     */
    private void waitReqConn() throws IOException {
        while(true) {
            clientChannel = serverChannel.accept();
            if(null != clientChannel) {
                System.out.println("新的连接接入!");
            }
            processReq(); //处理请求
            clientChannel.close();
        }
    }

    /**
     * 处理请求过来的数据
     * @throws IOException
     */
    private void processReq() throws IOException {
        System.out.println("开始读取和处理客户端数据. . .");
        buff.clear();
        clientChannel.read(buff);
        int result = intBuff.get(0) + intBuff.get(1);
        buff.flip();
        buff.clear();
        //修改视图,原来的缓冲区也会变化
        intBuff.put(0, result);
        clientChannel.write(buff);
        System.out.println("读取和处理客户端数据完成");
    }

    /**
     * 程序入口方法
     */
    public void start() {
        try {
            //打开服务通道
            openChannel();

            //监听等待客户端请求
            waitReqConn();

            clientChannel.close();
            System.out.println("服务端处理完毕");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new NIOChannelServer().start();
    }
}

客户端代码

package me.zhengzx.nio;

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

public class NIOChannelClient {
    private SocketChannel channel = null;

    private ByteBuffer buff = ByteBuffer.allocate(8);
    private IntBuffer intBuff = buff.asIntBuffer();

    //public Socket

    /**
     * 与服务器指定的地址和端口建立连接通道
     * @return
     * @throws IOException
     */
    private SocketChannel connect() throws IOException {
        return SocketChannel.open(new InetSocketAddress("localhost", 8888));

    }

    /**
     * 发送加法请求到服务器
     * @param a
     * @param b
     * @throws IOException
     */
    private void sendRequest(int a, int b) throws IOException {
        buff.clear();
        intBuff.put(0, a);
        intBuff.put(1, b);
        channel.write(buff);
        System.out.println("发送加法请求(" + a + "+" + b + ")");
    }

    /**
     * 接收服务器的运算结果
     * @throws IOException
     */
    private int receiveResult() throws IOException {
        buff.clear();
        channel.read(buff);
        return intBuff.get(0);
    }

    /**
     * 获得加法运算的结果
     * @param a
     * @param b
     * @return
     */
    private int getSum(int a, int b) {
        int result = 0;
        try {
            channel = connect();

            sendRequest(a, b);

            result = receiveResult();

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

    public static void main(String[] args) {
        int result = new NIOChannelClient().getSum(56, 34);
        System.out.println("加法运算的最后结果为:" + result);
    }
}

你可能感兴趣的:(NIO)