Socket的发送缓冲区大小为64512=63k,接收缓冲区大小为8192=8k,server端接收到client连接时启动一个线程,线程进入阻塞状态(接收第二个连接时才开始读取客户端数据),客户端程序开始读取本地文件(大于1M)往服务器发送数据,每次往输出流1k数据,发送到第80次时客户端也阻塞了,也就是前79次的数据要么已经到达服务器,要么在本地缓存,问题来了,79次*1k/次 - 客户端发送缓存63k - 服务器接收缓存8k = 8k,这8k数据在什么地方?
Server.java
private static CountDownLatch latch = new CountDownLatch(1);
public static void main(String[] args) throws Throwable
{
ServerSocket serverSocket = new ServerSocket(80);
int i = 1;
while (i++ <= 2)//等待两个客户端连接,第一个客户端连接将阻塞
{
new Thread(new Client(serverSocket.accept())).start();
}
latch.countDown();
serverSocket.close();
}
static class Client implements Runnable
{
Socket socket = null;
public Client(Socket socket) {
this.socket = socket;
}
@Override
public void run()
{
try{
//8192
System.out.println("socket.getReceiveBufferSize:" + socket.getReceiveBufferSize());
//64512
System.out.println("socket.getSendBufferSize:" + socket.getSendBufferSize());
//在第二个客户端连接前将一直阻塞
latch.await();
int len = -1;
byte[] b = new byte[8*1024];//每次读取8k
InputStream is = socket.getInputStream();
while((len = is.read(b)) > 0){
System.out.println(len);
}
}catch(Exception e){
e.printStackTrace();
}
try {socket.close();} catch (IOException e) {e.printStackTrace();}
}
}
Client.java
public static void main(String[] args) throws Throwable
{
Socket socket = new Socket("127.0.0.1", 80);
//64512
System.out.println("socket.getSendBufferSize:" + socket.getSendBufferSize());
//8192
System.out.println("socket.getReceiveBufferSize:" + socket.getReceiveBufferSize());
int len = -1;
byte[] b = new byte[1024];// 1k
InputStream is = new FileInputStream("c:/test.rar");// 大于1M
OutputStream os = socket.getOutputStream();
while ((len = is.read(b)) > 0) {
System.out.println(len);
os.write(b, 0, len);
//os.flush();
}
is.close();
socket.close();
}
来源:oschina
链接:https://my.oschina.net/u/1245084/blog/469841