用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - java代码库

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

2013-04-24 作者: 小蜜锋举报

[java]代码库

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();
                }
            }
        }

    }
}


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...