Netty学习一. 传统SocketIO服务端

2018-05-19  本文已影响0人  秋林格瓦斯

使用传统socket创建服务端,有两个阻塞处

结论: 导致单线程情况下只能有一个客户端连接,多线程池可以解决这种问题.但是非常消耗性能.

Tips:
客户端使用telnet连接; 格式: telent 127.0.0.1 18888 ;ctrl+] 回显内容,send 字符串发送文字

服务端代码如下:

package com.lee.io.OIO;

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;

/**
 * 
 * @author liguoping
 *
 * 2018年5月19日-下午9:39:20
 */
@SuppressWarnings("resource")
public class OioServer {
    
    public static void main(String[] args) throws Exception {
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(18888);
        System.out.println("服务端启动...");
        while(true){
            // 获取套接字(阻塞)
            final Socket socket = serverSocket.accept();
            newCachedThreadPool.execute(new Runnable() {
                
                public void run() {
                    System.out.println("新来一个客户端");
                    handler(socket);
                }
            });
            
        }
        
    }

    private static void handler(Socket socket){
        try {
            byte[] bytes = new byte[1024];
            InputStream inputStream = socket.getInputStream();
            while (true) {
                // 读取数据(阻塞)
                int read = inputStream.read(bytes);
                if (read != -1) {
                    System.out.println(new String(bytes, 0, read));
                } else {
                    break;
                }
            } 
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                System.out.println("关闭socket");
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    }
}

上一篇 下一篇

猜你喜欢

热点阅读