我正在尝试通过套接字实现基本通信,我现在拥有的是:
服务器开始监听套接字,
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)
我希望客户端在发送文件后阻止等待服务器响应,但是在发送文件后它突然以异常结束。我很确定我在简单流和对象流之间切换时做错了。
有人知道我应该改变什么才能让它工作吗?
先感谢您!