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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用Java的异步Socket服务器端的示例。它允许多个客户端同时连接并进行通信。 ```java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousChannelGroup; import java.nio.channels.AsynchronousServerSocketChannel; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class AsyncServer { private static final int PORT = 8080; private static final int THREAD_POOL_SIZE = 10; private AsynchronousServerSocketChannel serverSocketChannel; private ExecutorService executorService; private AsynchronousChannelGroup channelGroup; public AsyncServer() throws IOException { executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE); channelGroup = AsynchronousChannelGroup.withThreadPool(executorService); serverSocketChannel = AsynchronousServerSocketChannel.open(channelGroup); serverSocketChannel.bind(new InetSocketAddress(PORT)); System.out.println("Server started on port " + PORT); } public void start() { serverSocketChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Void>() { @Override public void completed(AsynchronousSocketChannel socketChannel, Void attachment) { // Accept the next connection serverSocketChannel.accept(null, this); // Handle this connection handleConnection(socketChannel); } @Override public void failed(Throwable exc, Void attachment) { System.err.println("Failed to accept connection"); } }); } private void handleConnection(AsynchronousSocketChannel socketChannel) { ByteBuffer buffer = ByteBuffer.allocate(1024); socketChannel.read(buffer, null, new CompletionHandler<Integer, Void>() { @Override public void completed(Integer result, Void attachment) { if (result == -1) { // Connection closed try { socketChannel.close(); } catch (IOException e) { System.err.println("Failed to close socket channel"); } return; } // Handle the received data buffer.flip(); byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); String data = new String(bytes); System.out.println("Received data: " + data); // Echo the data back to the client ByteBuffer outputBuffer = ByteBuffer.wrap(bytes); socketChannel.write(outputBuffer, null, new CompletionHandler<Integer, Void>() { @Override public void completed(Integer result, Void attachment) { // Continue reading data from the client buffer.clear(); socketChannel.read(buffer, null, this); } @Override public void failed(Throwable exc, Void attachment) { System.err.println("Failed to write data to client"); } }); } @Override public void failed(Throwable exc, Void attachment) { System.err.println("Failed to read data from client"); } }); } public void stop() throws IOException { serverSocketChannel.close(); channelGroup.shutdown(); executorService.shutdown(); System.out.println("Server stopped"); } public static void main(String[] args) throws IOException { AsyncServer server = new AsyncServer(); server.start(); } } ``` 这个示例使用JavaNIO2异步Socket通道和处理程序来处理输入/输出操作。它使用一个线程池来处理通道的读/写操作,从而允许处理多个客户端连接。在这个示例中,服务器将收到的数据回显给客户端。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值