【发布时间】:2011-11-11 04:16:04
【问题描述】:
我有一个客户端服务器应用程序,它有 16 个线程(8 个客户端,8 个服务器),每个线程都有一个 1-1 匹配的 TCP 连接(所以 8 个 TCP 流)。
我让服务器发送 X 数量的随机字节然后关闭。同时客户端只是读取 X 量的数据然后关闭。 X 是预先确定的。我也在使用 dummynet 进行带宽限制,但我正在为管道提供足够的带宽(100Mbps)。有时它工作正常,有时我得到这些例外。我在大约 3.5 分钟内将 1GB 均匀分布在所有 8 个连接上。
客户端抛出此异常:
java.net.SocketException: Operation timed out
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(SocketInputStream.java:129)
at miccbull.parralleltcp.client.StreamWorker.run(StreamWorker.java:43)
服务器抛出此异常:
java.net.SocketException: Broken pipe
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
at java.net.SocketOutputStream.write(SocketOutputStream.java:124)
at miccbull.parralleltcp.server.TransmissionWorker.run(TransmissionWorker.java:51)
服务器代码:
public void run() {
OutputStream os = null;
try {
socket = sSocket.accept();
os = socket.getOutputStream();
} catch (IOException e2) {
e2.printStackTrace();
}
//send the data
for(int i = 0; i < Server.TRANSMISSIONS; i++){
System.out.println(sSocket.getLocalPort() + " sending set " + (i+1) + " of " + Server.TRANSMISSIONS);
try {
os.write(new byte[Server.FILE_SIZE/Server.numStreams/Server.TRANSMISSIONS]);
os.flush();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Closing server (at write bytes) with socket id: " + sSocket.getLocalPort());
}
}
System.out.println("Worker " + sSocket.getLocalPort() + " done");
//close the socket
try {
socket.close();
sSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
客户代码:
public void run(){
byte[] bytes = new byte[1024]; //number of bytes to read per client stream
InputStream is = null;
//connect to server
try {
connectionSocket = new Socket("localhost", id);
is = connectionSocket.getInputStream();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//read file from server
int value = 0;
int bytesRead = 0;
try {
while(bytesRead < (Client.FILE_SIZE/Client.NUM_STREAMS)){
value = is.read(bytes, 0, 1024);
if(value == -1){
System.out.println("******************************** Read is -1 for client " + id);
}
else if(value == 0){
System.out.println("******************************** Read is 0 for client " + id);
}
bytesRead += value;
}
} catch (IOException e) {
System.out.println("**** Exception in read in client " + id + " and value value was: " + value);
if(bytesRead == (Client.FILE_SIZE/Client.NUM_STREAMS)){
System.out.println("************ NOT ACTUALLY BAD" + id);
}
e.printStackTrace();
}
//Finished download
Client.workerDone();
System.out.println("Worker " + id + " done received " + bytesRead);
导致这些异常的原因是什么?
【问题讨论】:
标签: java sockets exception tcp