Netty 2021 1129 阻塞IO 特点

 

 

 

 

 

 

 

2、实例 client-server

i)、SocketTcpBioServer 

import java.io.IOException;
import  java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SocketTcpBioServer {
    static byte[] bytes=new byte[1024];
    public static void main(String[] args) throws IOException {
        try {
            //1、创建ServerSocker
            final ServerSocket serverSocket=new ServerSocket();
            serverSocket.bind(new InetSocketAddress(8080));
            ExecutorService executorService=Executors.newCachedThreadPool();
            System.out.println("等客户端发送信息......");
            Socket socket=serverSocket.accept();
            int read=socket.getInputStream().read(bytes);
            String result=new String(bytes);
            System.out.println("服务端接受客户端消息:"+result);
           /* //2、等客户端发送信息
            while (true){
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                       try {
                           System.out.println("等客户端发送信息......");
                           Socket socket=serverSocket.accept();
                           int read=socket.getInputStream().read(bytes);
                           String result=new String(bytes);
                           System.out.println("服务端接受客户端消息:"+result);
                       }catch (Exception e){

                       }
                    }
                });

            }*/
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}

ii)、SocketTcpBioClient 

import  java.io.IOException;
import java.net.*;

public class SocketTcpBioClient {
    public static void main(String[] args) throws IOException {
        try {
            Socket socket=new Socket();
            SocketAddress address=new InetSocketAddress(InetAddress.getLocalHost(),8080);
            socket.connect(address);
            socket.getOutputStream().write("mayikt1".getBytes());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

iii)、输出

原文地址:https://www.cnblogs.com/smallfa/p/15627660.html