java服务端 客户端(非阻塞 多线程)

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用
public class MultithreadJIoSocketTest {
    @Test
    public void testMultithreadJIoSocket() throws Exception {
        ServerSocket serverSocket = new ServerSocket (10002);
        Thread thread = new Thread (new Accptor (serverSocket) );
        thread.start();

        Scanner scanner = new Scanner (System.in);
        scanner.next();
    }

    public class Accptor implements Runnable {
        private ServerSocket serverSocket;

        public Accptor (ServerSocket serverSocket) {
            this.serverSocket = serverSocket;
        }

        public void run() {
            while (true) {
                Socket socket = null;
                try {
                    socket = serverSocket.accept();
                    if (socket != null) {
                        System.out.println ("收到了socket:" + socket.getRemoteSocketAddress().toString() );
                        Thread thread = new Thread (new Processor (socket) );
                        thread.start();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public class Processor implements Runnable {
        private Socket socket;

        public Processor (Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream() ) );
                String readLine;
                while (true) {
                    readLine = in.readLine();
                    System.out.println ("收到消息" + readLine);
                    if ("end".equals (readLine) ) {
                        break;
                    }
                    //客户端断开连接
                    socket.sendUrgentData (0xFF);
                    Thread.sleep (5000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (SocketException se) {
                System.out.println ("客户端断开连接");
            } catch (IOException e) {
                e.printStackTrace();
            }
            finally {
                try
                {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:JS定时器

下一篇: 在spring中使用quartz的一个小例子