您需要通过某种数据格式将数据打包到流中.一种方法是使用常用的MIME数据格式,通常用于在电子邮件中发送附件.
供您参考,我刚刚从下面的问题复制了通过套接字发送和接收的代码.
File f = new File(path);
BufferedOutputStream out = new BufferedOutputStream( socket.getOutputStream() );
String filename=path.substring(path.lastIndexOf("/")+1);
// create a multipart message
MultipartEntity multipartContent = new MultipartEntity();
// send the file inputstream as data
InputStreamBody isb = new InputStreamBody(new FileInputStream(f), "image/jpeg", filename);
// add key value pair. The key "imageFile" is arbitrary
multipartContent.addPart("imageFile", isb);
multipartContent.writeTo(out);
out.flush();
out.close();
并使用MimeBodyPart作为JavaMail的一部分来回读下面的代码.
MimeMultipart multiPartMessage = new MimeMultipart(new DataSource() {
@Override
public String getContentType() {
// this could be anything need be, this is just my test case and illustration
return "image/jpeg";
}
@Override
public InputStream getInputStream() throws IOException {
// socket is the socket that you get from Socket.accept()
BufferedInputStream inputStream = new BufferedInputStream(socket.getInputStream());
return inputStream;
}
@Override
public String getName() {
return "socketDataSource";
}
@Override
public OutputStream getOutputStream() throws IOException {
return socket.getOutputStream();
}
});
// get the first body of the multipart message
BodyPart bodyPart = multiPartMessage.getBodyPart(0);
// get the filename back from the message
String filename = bodyPart.getFileName();
// get the inputstream back
InputStream bodyInputStream = bodyPart.getInputStream();
// do what you need to do here....