温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在java中使用SocketChannel实现一个客户端

发布时间:2021-04-22 15:53:39 来源:亿速云 阅读:149 作者:Leah 栏目:编程语言

怎么在java中使用SocketChannel实现一个客户端?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

常用的java框架有哪些

1.SpringMVC,Spring Web MVC是一种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架。2.Shiro,Apache Shiro是Java的一个安全框架。3.Mybatis,MyBatis 是支持普通 SQL查询,存储过程和高级映射的优秀持久层框架。4.Dubbo,Dubbo是一个分布式服务框架。5.Maven,Maven是个项目管理和构建自动化工具。6.RabbitMQ,RabbitMQ是用Erlang实现的一个高并发高可靠AMQP消息队列服务器。7.Ehcache,EhCache 是一个纯Java的进程内缓存框架。

1、步骤

(1)创建SocketChannel实例,并将其配置为非阻塞模式,只有在SocketChannel实例中,任何I/O操作都是非阻塞的。

(2)使用connect()方法连接服务器,同时使用while循环连续检测和完全连接。在需要立即进行I/O操作之前,必须使用finishConnect()来完成连接过程。

(3)用ByteBuffer读写字节,假如SelectableChannel是一种非阻塞模式,那么它的I/O操作读写字节可能比实际字节少,甚至没有。因此,我们使用循环连续的读写来确保读写完成。

2、实例

public class NonBlockingTCPClient {
    public static void main(String[] args) {
        byte[] data = "hello".getBytes();
        SocketChannel channel = null;
        try {
            // 1. open a socket channel
            channel = SocketChannel.open();
            // adjust to be nonblocking
            channel.configureBlocking(false);
            // 2. init connection to server and repeatedly poll with complete
            // connect() and finishConnect() are nonblocking operation, both return immediately
            if (!channel.connect(new InetSocketAddress(InetAddress.getLocalHost(), 8899))) {
                while (!channel.finishConnect()) {
                    System.out.print(".");
                }
            }
 
            System.out.println("Connected to server...");
 
            ByteBuffer writeBuffer = ByteBuffer.wrap(data);
            ByteBuffer readBuffer = ByteBuffer.allocate(data.length);
            int totalBytesReceived = 0;
            int bytesReceived;
            // 3. read and write bytes
            while (totalBytesReceived < data.length) {
                if (writeBuffer.hasRemaining()) {
                    channel.write(writeBuffer);
                }
                if ((bytesReceived = channel.read(readBuffer)) == -1) {
                    throw new SocketException("Connection closed prematurely");
                }
                totalBytesReceived += bytesReceived;
                System.out.print(".");
            }
            System.out.println("Server said: " + new String(readBuffer.array()));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 4 .close socket channel
            try {
                if (channel != null) {
                    channel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI