【发布时间】:2016-01-06 18:08:31
【问题描述】:
每当我尝试从套接字读取输入流时,我的套接字客户端就会挂起。
DataInputStream dis = new DataInputStream(socket.getInputStream());
int singleByte;
while((singleByte = dis.read()) != -1) { //<-- hangs here
char c = (char)singleByte;
// append character
message_string += c;
}
- 挂在
while((singleByte = dis.read()) != -1) {
我已确认服务器正在回显我以原始 ASCII 发送的内容。
我不明白什么?为什么尝试读取服务器响应时挂起?
服务器端(处理请求):
class HandleInputBuffer implements Runnable {
private String msg = "";
private String response = "8";
public HandleInputBuffer(String str) {
this.msg = str;
}
@Override
public void run() {
String exception_msg = "";
// process incoming message
try {
if(msg!=null){
if(msg.length()>0){
// create and send reply
String response = "8";
// ****************************
// create and send response
// ****************************
try {
response = msg;
output_stream = new DataOutputStream(client_socket.getOutputStream());
output_stream.writeInt(response.getBytes("US-ASCII").length);
output_stream.write(response.getBytes("US-ASCII"));
output_stream.flush();
output_stream.close();
//client_socket.shutdownOutput();
client_socket.close();
} catch (IOException e) {
e.printStackTrace();
try{output_stream.flush();} catch (IOException e1) {}
try {client_socket.close();} catch (IOException e1) {}
try {updateConversationHandler = new Handler();} catch (Exception e1) {}
return;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
客户端重构 - 此代码挂起 int length = dis.readInt();
InetAddress serverAddr = InetAddress.getByName(edit_ip_address.getText().toString());
if(socket == null){
socket = new Socket(serverAddr, Integer.parseInt(edit_port.getText().toString()));
}
// send bytes
output_stream = new DataOutputStream(socket.getOutputStream());
output_stream.write(command.getBytes("US-ASCII"));
DataInputStream dis = new DataInputStream(socket.getInputStream());
int length = dis.readInt();
byte[] buffer = new byte[length]; //<-- OutOfMemoryException
dis.readFully(buffer);
for (byte b:buffer){
char c = (char)b;
message_string += c;
}
【问题讨论】:
-
@Kayaman 是的,输出流在写入后立即被刷新。
-
um .... 你的例子没有编译,DataInputStream#read 需要一个参数
-
@specializt 嗯,不,它没有:有三个重载,分别有零、一个和三个参数。
-
@specializt - 我对编译没有任何问题。我的代码编译得很好——这就是我知道它正在读取的方式。我不知道还能告诉你什么。
-
@specializt 是的:检查从
FilterInputStream.继承的方法你应该阅读你的链接而不是假设事情。也没有弃用的 API。
标签: java datainputstream