【发布时间】:2015-04-17 13:44:47
【问题描述】:
我无法通过使用 writeUTF("String") 的套接字与客户端使用 readUTF() 收听消息进行对话。
到目前为止,它按我的意愿工作。但是,在添加从客户端接收文件的代码后,我无法向客户端发送任何消息。代码如下。已经好几天了……谁能帮我解决这个问题?感谢您的意见:-)
// 客户端.java
String ack = in.readUTF();
println(ack); // "How do you do?"
String aack = in.readUTF();
println(aack); // HANGING FOREVER
// 服务器.java
Socket server = serverSocket.accept();
DataInputStream in = new DataInputStream(server.getInputStream());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
// CAN SEND MESSAGES
out.writeUTF("How do you do? "+ "\r\n");
out.flush();
// AFTER THIS SEGMENT CANNOT WRITE TO CLIENT ANYMORE
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
byte [] byteArray = new byte [FILE_SIZE];
InputStream is = server.getInputStream();
fos = new FileOutputStream(FILE_TO_RECEIVED);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(byteArray,0,byteArray.length);
current = bytesRead;
do {
bytesRead =
is.read(byteArray, current, (byteArray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(byteArray, 0 , current);
bos.flush();
System.out.println("File " + FILE_TO_RECEIVED
+ " downloaded (" + current + " bytes read)");
}
finally {
if (fos != null) fos.close();
if (bos != null) bos.close();
}
// WORKS ALRIGHT UP TO THIS PART
// PROBLEM BEGINS...
// CANNOT
// SEND MASSAGE ANYMORE
// CLIENT WAIT FOR MSG HANGING FOREVER
out.writeUTF("Can you hear?"+ "\r\n");
out.flush();
【问题讨论】:
-
OutputStream os = server.getOutputStream(); PrintWriter pw = new PrintWriter(os, true); pw.println("你叫什么名字?");这解决了我的问题。