标签:
这是用scala实现的一个简单的文件传输程序。
package jpush import java.io.{DataInputStream, File, FileOutputStream} import java.net.ServerSocket import scala.collection.JavaConversions._ /** * Created by dingb on 2016/6/3. */ object Server extends App { def port = 8899 override def main(args: Array[String]) { val roots = args.toList match { case Nil => List(new File(System.getProperty("user.dir"))) case _ => args.map(new File(_)).toList } printf("dst root is %s\n", roots.mkString(",")) val ss = new ServerSocket(port) def accept: Unit = { val s = ss.accept() printf("%s in \n", s.getRemoteSocketAddress); async { val dis = new DataInputStream(s.getInputStream) val fn = dis.readUTF val size = dis.readLong printf("loading %s %d\n", fn, size); if(size > 0) { roots.foreach(new File(_, fn).getParentFile.mkdirs()) val oses = roots.map(new File(_, fn)).map(new FileOutputStream(_)) val buf = new Array[Byte](1024) var done = false while(!done) { val r = dis.read(buf) if(r <= 0) done = true else oses.foreach(_.write(buf, 0, r)) } oses.foreach(_.close) } } accept } accept } def async(body : => Unit) = { val t = new Thread(new Runnable { override def run(): Unit = { body } }) t.start() } }
package jpush import java.io.{DataOutputStream, File, FileInputStream} import java.net.Socket /** * Created by dingb on 2016/6/3. */ object Client extends App{ def send_file(ip: String, file: File, top: String): Unit = { val fis = new FileInputStream(file) val s = new Socket(ip, Server.port) val dos = new DataOutputStream(s.getOutputStream) val remotename = top + File.separator + file.getName printf("sending %d bytes %s to %s\n", file.length(), file.getAbsolutePath, remotename) dos.writeUTF(remotename) dos.writeLong(file.length()) val buf = new Array[Byte](1024) var done = false while(!done) { val r = fis.read(buf) if(r <= 0) done = true else dos.write(buf, 0, r) } dos.close() fis.close() s.close() } def send(ip: String, file: File, top: String): Unit = { if(file.isDirectory) file.listFiles().foreach(send(ip, _, "" + File.separator + file.getName)) else send_file(ip, file, top) } override def main(args: Array[String]) { if(args.length < 1) usage() else args.drop(1).map(new File(_)).foreach(send(args(0), _, "")) } def usage(): Unit = { println("usage: jpsh.Client <ip> [file]...") System.exit(-1) } }
https://github.com/dingbig/jpush
用scala实现一个基于TCP Socket的快速文件传输程序
标签:
原文地址:http://www.cnblogs.com/dingdaheng/p/5557494.html