Socket-客户端和服务端通信

发布时间:2024年01月16日

服务端

import java.io.IOException;
import java.net.InetSocketAddress;
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.nio.charset.StandardCharsets;
import java.util.Iterator;

public class ServerSocket {
    public static void main(String[] args) throws IOException {
        //创建选择器
        Selector selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(Boolean.FALSE);
        serverSocketChannel.bind(new InetSocketAddress(8888));
        SelectionKey selectionKey = serverSocketChannel.register(selector, 0, null);
        selectionKey.interestOps(SelectionKey.OP_ACCEPT);
        while(true){
            int result = selector.select();
            /*
             *事件是以selectionkey对象方式存入集合,每一个selectionkey对应一个实际操作
             */
            Iterator<SelectionKey> selectionKeyIterator = selector.selectedKeys().iterator();
            /*
             *移除事件,防止下次继续处理导致异常
             */
            while(selectionKeyIterator.hasNext()){
                SelectionKey key = selectionKeyIterator.next();
                selectionKeyIterator.remove();
                if(key.isAcceptable()){
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    SocketChannel client = server.accept();
                    client.configureBlocking(Boolean.FALSE);
                    ByteBuffer byteBuffer = ByteBuffer.allocate(16);
                    SelectionKey selectionKey1 = client.register(selector, 0, byteBuffer);
                    selectionKey1.interestOps(SelectionKey.OP_READ);
                    System.out.println("链接成功" + client);
                }else if(key.isReadable()){ //客户端断开也会
                    try{
                        SocketChannel socketChannel = (SocketChannel) key.channel();
                        ByteBuffer buffer = (ByteBuffer) key.attachment();
                        int read = socketChannel.read(buffer);
                        //read==-1 客户端断开
                        if(read == -1){
                            //如果不取消,服务端会一直向事件队列添加事件,因此会导致即使key被移除,会被服务端再次添加
                            key.cancel();
                        }else{
                            buffer.flip();
                            if(buffer.limit() == buffer.capacity()){
                                ByteBuffer buffer1 = ByteBuffer.allocate(buffer.capacity() * 2);
                                buffer1.put(buffer);
                                key.attach(buffer1);
                            }else{
                                System.out.println(StandardCharsets.UTF_8.decode(buffer));
                                buffer.clear();
                            }
                        }

                    }catch (Throwable e){
                        //反注册
                        key.cancel();
                    }
                }

            }
        }





    }
}

客户端

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class ClientSocket {
    public static void main(String[] args) throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost", 8888));
        System.out.println(socketChannel.isConnected());
        Scanner scanner = new Scanner(System.in);
        while(true){
            String content = scanner.next();
            socketChannel.write(StandardCharsets.UTF_8.encode(content));
        }
    }
}

效果:
客户端发送信息 “你好啊!”
在这里插入图片描述
服务端接收信息
在这里插入图片描述

文章来源:https://blog.csdn.net/sunboylife/article/details/135627578
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。