传统Socket

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36381640/article/details/82660503
package com.gsau.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;

/**
 * @Description:
 * @Date: 2018/9/12 13:22
 * @author: wgq
 * @version: 1.0
 * @param:
 */
public class OioServer {
    @SuppressWarnings("resource")
    public static void main(String[] args) throws Exception {
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        ServerSocket server = new ServerSocket(10101);              //创建socket服务,监听10101端口
        System.out.println("服务器启动!");
        while (true) {
            final Socket socket = server.accept();                   //获取一个套接字(阻塞)
            System.out.println("来个一个新客户端!");
            newCachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    handler(socket);                                 //业务处理
                }
            });
        }
    }

   /**
   * @Description: 处理句柄
   * @Date: 2018/9/12 14:00
   * @author: wgq
   * @version: 1.0
   * @param: 
   */
    public 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();
            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36381640/article/details/82660503
今日推荐