Netty学习(2) BIO实现服务端

BIO编写的Server端实例:

package com.nettyStudy.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOServer {
    public static void main(String[] args) throws IOException {

        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(5555);
        System.out.println("服务器启动了");

        while(true){
            final Socket socket = serverSocket.accept();
            System.out.println("一个客户端连接");
            executorService.execute(()->{
                try {
                    handelSocket(socket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    private static void handelSocket(Socket socket) throws IOException {
        System.out.println("处理客户端连接的线程name:"+Thread.currentThread().getName());
        InputStream inputStream = socket.getInputStream();
        byte[] bytes = new byte[1024];
        while (true){
            int read = inputStream.read(bytes);
            if(read != -1){
                System.out.println(new String(bytes,0,read));
            }else{
                break;
            }
        }
    }
}

发布了52 篇原创文章 · 获赞 8 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/wufengui1315/article/details/103514571
今日推荐