NIO(五) - 阻塞試Socket通訊

package com.xbb.demo;

import org.junit.Test;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class SocketNonBlockingDemo {

    /**
     * 客戶端
     */
    @Test
    public void client(){
        try(
                SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",9999));
                ){
            ByteBuffer buf = ByteBuffer.allocate(1024);
            String msg = "你好,主子";
            buf.put(msg.getBytes());
            buf.flip();
            socketChannel.write(buf);
            socketChannel.shutdownOutput();
            while(socketChannel.read(buf) != -1){
                buf.flip();
                System.out.println(new String(buf.array(),0,buf.limit()));
                buf.clear();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 服務端
     */
    @Test
    public void server(){
        try(
                ServerSocketChannel socketChannel = ServerSocketChannel.open();
                ){
            socketChannel.bind(new InetSocketAddress(9999));
            SocketChannel channel = socketChannel.accept();
            ByteBuffer buf = ByteBuffer.allocate(1024);
            while(channel.read(buf) != -1){
                buf.flip();
                System.out.println("來自客戶端的消息 : " + new String(buf.array(),0,buf.limit()));
                buf.clear();
            }
            channel.shutdownInput();
            String msg = "你也好,孫子";
            buf.put(msg.getBytes());
            buf.flip();
            channel.write(buf);
        }catch (Exception e){
            e.printStackTrace();
        }
    }



}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章