为了账号安全,请及时绑定邮箱和手机立即绑定

网络

标签:
Java

1. 阻塞接口

服务端

@Test
public void testServer() throws IOException {
   //创建socket,bind,listen都在构造函数中触发.
   ServerSocket server = new ServerSocket(10086);
   boolean accept = true;
   while(accept){
       //接受连接
       Socket client = server.accept();
       System.out.println("accept client: "+client.getInetAddress());

       OutputStream outStream = null;
       InputStream inStream = null;
       try {
           //read
           inStream = client.getInputStream();
           byte[] buf = new byte[100];
           int ret = inStream.read(buf);	//阻塞的
           System.out.println("read return: " + ret);
           if(ret <= 0){
               client.close();
               System.out.println("client closed ...");
           }
           System.out.println("recv data: " + new String(buf));

           //write
           outStream = client.getOutputStream();
           outStream.write(buf);
       } catch (Exception e) {
           e.printStackTrace();
       }finally{
           inStream.close();
           outStream.close();
       }
   }
   server.close();
} 

客户端

@Test
public void testClient() throws IOException {
	//创建socket
	Socket client = new Socket("127.0.0.1", 10086);
    //write
    try {
        OutputStream outStream = client.getOutputStream();
        outStream.write("sicwen".getBytes());
        Thread.sleep(1000);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        client.close();
    }
}

2. 非阻塞接口
服务端

@Test
public void testServer() throws IOException {
    int clientNum = 0;

    Selector select = Selector.open();

    ServerSocketChannel svrSocketChannl = ServerSocketChannel.open();
    InetSocketAddress hostAddress = new InetSocketAddress("127.0.0.1", 10086);
    svrSocketChannl.bind(hostAddress);

    //添加服务器的监听套接字
    svrSocketChannl.configureBlocking(false);
    int ops = svrSocketChannl.validOps();
    svrSocketChannl.register(select, ops, null);

    while (true) {
        select.select();
        Set<SelectionKey> selectKeys = select.selectedKeys();
        Iterator<SelectionKey> ite = selectKeys.iterator();
        while (ite.hasNext()) {
            SelectionKey ky = (SelectionKey) ite.next();
            if (ky.isAcceptable()) {
                //因为只有ServerSocketChannel才能接收新请求, 所以使用svrSocketChannl来accept
                SocketChannel clientChannel = svrSocketChannl.accept();
                clientChannel.configureBlocking(false);
                //将新的客户Channel注册到selector上
                clientChannel.register(select, SelectionKey.OP_READ);
                System.out.println("Accept a new Client: " + clientNum++);
            } else if (ky.isReadable()) {
                SocketChannel clientChannel = (SocketChannel) ky.channel();
                ByteBuffer buff = ByteBuffer.allocate(48);
                int ret = 0;
                try {
                    ret = clientChannel.read(buff);
                } catch (Exception e) {
                    ky.cancel();
                    clientChannel.close();
                    System.out.println("client has been force closed...");
                }
                if (ret <= 0) {
                    if (ky.isValid()) {
                        ky.cancel();
                        clientChannel.close();
                        System.out.println("client has been closed...");
                    }
                } else {
                    try {
                        ByteBuffer sendBuff = ByteBuffer.allocate(7);
                        sendBuff.put("1234560".getBytes());
                        sendBuff.flip();
                        if (clientChannel.write(sendBuff) <= 0) {
                            System.out.println("send data faild");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else if (ky.isWritable()) {
                System.out.println("is Writeable");
            }
            ite.remove();
        }
    }
}

客户端

@Test
public void testClient() throws IOException {
    //创建socket
    Socket client = new Socket("127.0.0.1", 10086);
    //write
    try {
        OutputStream outStream = client.getOutputStream();
        outStream.write("sicwen".getBytes());

        InputStream is = client.getInputStream();
        byte[] buff = new byte[14];
        int ret = is.read(buff);
        if(ret > 0){
            System.out.println(new String(buff));
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        client.close();
    }
}
点击查看更多内容
2人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
1
获赞与收藏
31

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消