Why do SocketChannel writes always complete for the full amount even on non-blocking sockets?

技术标签: java.  插座  网络编程  nio

Using the Sun Java VM 1.5 or 1.6 on Windows, I connect a non-blocking socket. I then fill a ByteBuffer with a message to output, and attempt to write() to the SocketChannel.

I expect the write to complete only partially if the amount to be written is greater than the amount of space in the socket's TCP output buffer (this is what I expect intuitively, it's also pretty much my understanding of the 译文), but that's not what happens.这 write() 总是 seems to return reporting the full amount written, even if it's several megabytes (the socket's SO_SNDBUF is 8KB, much, much less than my multi-megabyte output message).

A problem here is that I can't test the code that handles the case where the output is partially written (registering an interest set of WRITE to a selector and doing a select() to wait until the remainder can be written), as that case never seems to happen. What am I not understanding?

看答案

I managed to reproduce a situation that might be similar to yours. I think, ironically enough, your recipient is consuming the data faster than you're writing it.

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer {
  public static void main(String[] args) throws Exception {
    final ServerSocket ss = new ServerSocket(12345);
    final Socket cs = ss.accept();
    System.out.println("Accepted connection");

    final InputStream in = cs.getInputStream();
    final byte[] tmp = new byte[64 * 1024];
    while (in.read(tmp) != -1);

    Thread.sleep(100000);
  }
}



import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class MyNioClient {
  public static void main(String[] args) throws Exception {
    final SocketChannel s = SocketChannel.open();
    s.configureBlocking(false);
    s.connect(new InetSocketAddress("localhost", 12345));
    s.finishConnect();

    final ByteBuffer buf = ByteBuffer.allocate(128 * 1024);
    for (int i = 0; i < 10; i++) {
      System.out.println("to write: " + buf.remaining() + ", written: " + s.write(buf));
      buf.position(0);
    }
    Thread.sleep(100000);
  }
}

If you run the above server and then make the above client attempt to write 10 chunks of 128 kB of data, you'll see that every write operation writes the whole buffer without blocking. However, if you modify the above server not to read anything from the connection, you'll see that only the first write operation on the client will write 128 kB, whereas all subsequent writes will return 0

Output when the server is reading from the connection:

to write: 131072, written:  131072
to write: 131072, written:  131072
to write: 131072, written:  131072
...

Output when the server is not reading from the connection:

to write: 131072, written:  131072
to write: 131072, written:  0
to write: 131072, written:  0
...  

智能推荐

The user operation is waiting for ... "..." to complete

问题描述: 在Eclipse中maven项目jetty启动crm项目,弹出这个窗口,一直停留在这个状态,(没有启动项目中的工程,之前也存在我的工作空间中,并没有报错) 后来,尝试关闭这个报错的工程,关掉后运行,还是存在这个问题 后来,尝试删除这个工程,也关不掉,弹出delete resources ,报错 勉强解决:重新启动Eclipse,启动项目,可以启动了...

Why UI correction note always has a big static size

Prerequisite knowledge A simple tool to calculate the total size of a BSP application Some more technical details about SAP note My Analysis Take this simple note for example: Sara has only changed tw...

Why do hash functions use prime numbers?

https://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/     In a previous post i pointed out how questions posted in reward based discussions sites ...

NAT: Why Do We Need It?

NAT, which is critical to the IPv4 networks we still use today, has been hotly debated as the IPv6 grows with more addresses. However, since the IPv6 is not full-fledged, the existence of NAT still ma...

Why Do We Use Fiber Optic Switch?

A fiber optic switch is a device of transferring signal and data through fiber optic cables and optical modules. Compared to copper cables, the speed of data transmission is faster and more efficient....

猜你喜欢

Why do hash functions use prime numbers?

2019独角兽企业重金招聘Python工程师标准>>> In a previous post i pointed out how questions posted in reward based discussions sites likestackoverflow.com never gets answered satisfactorily. Th...

原型对象,原型链

函数都有prototype属性,它指向原型对象。 实例对象有__proto__属性,它指向对象原型 每一个原型对象都有constructor输赢,指向构造函数,每一个原型对象又具有__proto__属性,这个指向Object.prototype.在这里插入图片描述...

Node 调用 dubbo 服务的探索及实践

2.Dubbo简介 2.1 什么是dubbo Dubbo是一款高性能、轻量级的开源Java RPC框架,它提供了三大核心能力:面向接口的远程方法调用,智能容错和负载均衡,以及服务自动注册和发现。 2.2 流程图 Provider : 暴露服务的服务提供方。 Consumer : 调用远程服务的服务消费方。 Registry : 服务注册与发现的注册中心。 Monito...

mysql总结

mysql基础入门的总结     关于数据库:     数据库是软件开发人员要掌握的基本工具,软件的运行的过程就是操作数据的过程,数据库中的数据无非就是几个操作:增-删-查-改。         Mysql安装完成后,需要配置变量环境,找到配置路径path,然后把mysql安装目录bin文件导入就可以了。 然后运行cm...

adb及monkey常用命令

adb常用命令: 查看手机是否连接:adb devices   连接设备:adb connect 设备ip:端口号  若有连接多个设备需指明设备ip及端口号 安装APP:adb install [-r] 包名  -r表示覆盖安装,首次安装可省略 卸载APP:adb uninstall 包名 列出设备中所有应用包名:adb shell pm list packages ...

问答精选

Correctly formatting GCM notifications?

I'm currently trying out the google cloud messaging service with its sample application "Guestbook." https://developers.google.com/cloud/samples/mbs/ I'm attempting to send notifications tha...

Are there any performance benefits of using Asynchronous functions over Synchronous in Node Js?

Now I came across an article that distinguishes between an Asynchronous function and Synchronous functions. From my understanding of the different examples and explanations, synchronous functions are ...

Python: Costing calculator output

Good day all I'm busy creating a small costing calculator for the signage department. I'm not getting the calculator to output the amount. Brief Description: You enter the height and width and then wh...

Flask-SQLAlchemy - model has no attribute 'foreign_keys'

I have 3 models created with Flask-SQLalchemy: User, Role, UserRole role.py: user.py: user_role.py: If I try (in the console) to get all users via User.query.all() I get AttributeError: 'NoneType' obj...

Seeding many PRNGs, then having to seed them again, what is a good quality approach?

I have many particles that follow an stochastic process in parallel. For each particle, there is a PRNG associated to it. The simulation must go through many repetitions to get average results. For ea...

相关问题

相关文章

热门文章

推荐文章

相关标签

推荐问答