我正在尝试通过套接字实现基本通信,我现在拥有的是:
服务器启动侦听套接字,
this.serverSocket_ = new ServerSocket(this.serverPort_);
clientSocket = this.serverSocket_.accept();
客户端连接,服务器启动单独的线程以与该客户端一起运行,
打开对象输出和输入流,
out = new ObjectOutputStream(clientSocket_.getOutputStream());
out.flush();
in = new ObjectInputStream(clientSocket_.getInputStream());
客户端在该流上发送两个i Doubles,String和Long(在每个流之后刷新),
out.writeObject(conf_);
out.flush();
out.writeObject(supp_);
out.flush();
out.writeObject(separator_);
out.flush();
out.writeObject(new Long(dataFile_.length()));
out.flush();
服务器通过先前打开的流成功接收这些对象,
conf_ = (Double) in_.readObject();
supp_ = (Double) in_.readObject();
separator_ = (String) in_.readObject();
fileSize_ = (Long) in_.readObject();
现在是“困难的部分”,
客户端想要发送文件,因此打开不同的输出流(不是对象输出流)并发送文件,
FileInputStream fis = new FileInputStream(dataFile_);
BufferedInputStream bis = new BufferedInputStream(fis);
OutputStream os = clientSocket_.getOutputStream();
while (current < fileSize) {
bytesRead = bis.read(mybytearray, 0, mybytearray.length);
if (bytesRead >= 0) {
os.write(mybytearray, 0, mybytearray.length);
current += bytesRead;
}
progressBar_.setValue(current);
progressBar_.repaint();
}
os.flush();
服务器接收文件(也使用简单的输入流而不是ObjectInputStream),
int bytesRead;
int current = 0;
tmpFile_ = File.createTempFile("BasketAnalysis", "rec.dat");
byte[] mybytearray = new byte[fileSize];
InputStream is = clientSocket_.getInputStream();
FileOutputStream fos = new FileOutputStream(tmpFile_);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray, 0, mybytearray.length);
current = bytesRead;
do {
bytesRead = is.read(mybytearray, current,
(mybytearray.length - current));
if (bytesRead >= 0)
current += bytesRead;
} while ((bytesRead > -1) && (current < fileSize));
bos.write(mybytearray, 0, current);
bos.flush();
bos.close();
到目前为止一切正常,接收到文件,但现在服务器对该文件执行一些耗时的处理,之后将响应结果发送给客户端,
String resp = new String("Some processing result...");
out_.writeObject(resp);
out_.flush();
客户端应该接收完成整个通信的结果,
String message = (String) in.readObject();
Console.info("server > " + message);
不幸的是,客户端的最后一步失败,但有例外:
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at basketAnalysis.client.Client.run(Client.java:74)
at java.lang.Thread.run(Unknown Source)
我希望客户端在发送文件后阻止等待服务器响应,但在发送文件后突然完成异常。我很确定在简单流和对象流之间切换时我做错了。
有人知道我应该改变什么以使其有效吗?
提前谢谢!
答案 0 :(得分:3)
我认为你的基本误解就在这里:
客户希望发送文件,因此打开不同的输出流
OutputStream os = clientSocket_.getOutputStream();
这不会打开不同的输出流 - 这将获得对已经包含在{{1}中的相同输出流的另一个引用}。如果您需要两个数据流,则需要打开两个单独的连接。