setSoLinger是當socket在關閉時對當前未發送給對方數據的一種控制方式。java
一、setSoLinger(true, 0),表示無論當前有沒有還未發送給對方的數據就直接關閉連接。socket
二、setSoLinger(true, 1),表示等待1秒若是還有未發送給對方的數據也直接關閉連接。.net
三、setSoLinger(false, -1),表示不管如何都等未發送給對方的數據發送完畢才按照4次揮手的過程正常關閉連接。server
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;blog
public class SocketTest {get
public static void main(String[] args) throws Exception {
new Thread() {
public void run() {
try {
server();
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
startClient();
}it
public static void startClient() throws Exception {io
Socket s = new Socket();
InetSocketAddress i = new InetSocketAddress(7777);
try {
s.connect(i);
s.setSoLinger(true, 0);
Thread.sleep(1000);
s.getOutputStream().write(new byte[1000000]);
s.close();
} catch (IOException e) {
e.printStackTrace();
}class
}import
public static void server() throws Exception {
ServerSocket ss = new ServerSocket(7777, 5);
Socket s = ss.accept();
try {
InputStream in = s.getInputStream();
BufferedInputStream bi = new BufferedInputStream(in);
byte[] buf = new byte[1024];
int read = -1;
long total = 0;
while ((read = bi.read(buf)) != -1) {
total += read;
}
System.out.println("共讀取字節數爲:" + total);
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
上面的代碼表示第一種狀況,服務端在讀取數據時會發生以下鏈接異常: