我知道 Scala 使用 Java 套接字,但我不太明白人们在 Java 中遇到的同样问题的问题的答案。
这是我的代码:
我试图通过套接字发送 jar 文件,但是当我尝试从另一端打开 jar 文件时,该文件似乎已损坏。我该如何解决这个问题?
服务器:
object server extends App {
import java.net._
import java.io._
import scala.io._
import scala.io.Source
val server = new ServerSocket(9999)
//Master should ping the slave actor to request for jar file
while (true) {
val s = server.accept()
val in = new BufferedSource(s.getInputStream()).getLines()
val out = new PrintStream(s.getOutputStream())
val filename = "mapReduce.jar"
for (line <- Source.fromFile(filename, "ISO-8859-1").getLines) {
out.println(line)
// println(line)
}
out.flush()
s.close()
}
}
与客户一起:
object client extends App {
import java.net._
import java.io._
import scala.io._
import java.util.jar._
val s = new Socket(InetAddress.getByName("localhost"), 9999)
lazy val in = new BufferedSource(s.getInputStream()).getLines()
val out = new PrintStream(s.getOutputStream())
out.println("Give me the jar file!")
out.flush()
val file = new File("testmapReduce.jar")
val bw = new BufferedWriter(new FileWriter(file))
while(in.hasNext) {
val buf = in.next()
bw.write(buf)
// println(buf)
}
s.close()
bw.close()
println("Done!")
val jar = new JarFile(file) //this part fails
}
最佳答案
Source
、PrintStream
等旨在处理文本,而不是二进制数据。他们根据所使用的字符集(在您的情况下为“iso-8859-1”)转换读取和写入的数据。
不要使用它们来读取/写入二进制数据。
如果您只需要发送字节,则不必费心解释它们:
val f = new FileInputStream(filename)
val bos = new BufferedOutputStream(out)
Stream.continually(f.read).takeWhile(_ != -1).foreach(bos.write)
f.close
bos.close
关于java - 通过 Scala 中的套接字发送 Jar 文件时会损坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40947936/