Apache Mina 源码再读4 IoSession.write()源码剖析

在IoSession 中提供两个接口供写入数据。


Writes the specified message to remote peer. This operation is asynchronous; IoHandler.messageSent(IoSession,Object) will be invoked when the message is actually sent to remote peer. You can also wait for the returned WriteFuture if you want to wait for the message actually written.




When you implement a client that receives a broadcast message from a server such as DHCP server, the client might need to send a response message for the broadcast message the server sent. Because the remote address of the session is not the address of the server in case of broadcasting, there should be a way to specify the destination when you write the response message. This interface provides write(Object, SocketAddress) method so you can specify the destination.


1、WriteFuture write(Object message)  

2、WriteFuture write(Object message,  SocketAddress destination)

1、写入指定的消息对象到远程对端。写入操作是异步的。 当消息实际被写入远程对端时,IoHandler.messageSent(IoSession,Object)方法将被执行。 也可以,等待返回WriteFuture直到消息被写入到远程对端。

2、当消息从一个服务器端被广播到客户端时,例如:消息从DHCP服务器端广播到客户端时,如果客户端想返回一个相应消息给服务器端,可以是用destination 指定目的地。



 public WriteFuture write(Object message, SocketAddress remoteAddress) {
        if (message == null) {
            throw new IllegalArgumentException("Trying to write a null message : not allowed");
        }

        // We can't send a message to a connected session if we don't have
        // the remote address
        if (!getTransportMetadata().isConnectionless() && (remoteAddress != null)) {
            throw new UnsupportedOperationException();
        }

        // If the session has been closed or is closing, we can't either
        // send a message to the remote side. We generate a future
        // containing an exception.
        if (isClosing() || !isConnected()) {
            WriteFuture future = new DefaultWriteFuture(this);
            WriteRequest request = new DefaultWriteRequest(message, future, remoteAddress);
            WriteException writeException = new WriteToClosedSessionException(request);
            future.setException(writeException);
            return future;
        }

        FileChannel openedFileChannel = null;

        // TODO: remove this code as soon as we use InputStream
        // instead of Object for the mes
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值