This is a simple File transfer program implemented in Scala.
Service side
PackageJpushImportjava.io. {datainputstream, File, FileOutputStream}ImportJava.net.ServerSocketImportscala.collection.javaconversions._/*** Created by DINGB on 2016/6/3. */Object ServerextendsApp {def port= 8899override def main (Args:array[string]) {val roots=args.tolist Match { CaseNil = List (NewFile (System.getproperty ("User.dir"))) Case_ = = Args.map (NewFile (_)). ToList} printf ("DST Root is%s\n", roots.mkstring (",")) Val SS=NewServerSocket (port) def Accept:unit={val s=ss.accept () printf ('%s in \ n ', s.getremotesocketaddress); Async {val Dis=NewDataInputStream (S.getinputstream) val fn=Dis.readutf val Size=Dis.readlong printf ("Loading%s%d\n", FN, size); if(Size > 0) {Roots.foreach (NewFile (_, FN). Getparentfile.mkdirs ()) Val OSes= Roots.map (NewFile (_, FN)). Map (NewFileOutputStream (_)) Val buf=NewArray[byte] (1024) var done=false while(!Done ) {val R=Dis.read (BUF)if(r <= 0) Done =true ElseOses.foreach (_.write (buf, 0, R)) } Oses.foreach (_.close)}}} Accept} def async (body:= Unit) ={val T=NewThread (NewRunnable {override def run (): Unit={Body}}) T.start ()}}
Client
PackageJpushImportjava.io. {DataOutputStream, File, FileInputStream}ImportJava.net.Socket/*** Created by DINGB on 2016/6/3. */Object Clientextendsapp{def send_file (ip:string, File:file, top:string): Unit={val fis=NewFileInputStream (file) Val s=NewSocket (IP, server.port) Val dos=NewDataOutputStream (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=NewArray[byte] (1024) var done=false while(!Done ) {val R=Fis.read (BUF)if(r <= 0) Done =true ElseDos.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))Elsesend_file (IP, file, top)} override def main (args:array[string]) {if(Args.length < 1) usage ()ElseArgs.drop (1). Map (NewFile (_)). foreach (Send (args (0), _, "")) } def usage (): Unit={println ("Usage:jpsh. Client <ip> [file] ... ") System.exit (-1) }}
Source code Download
Https://github.com/dingbig/jpush
Using Scala to implement a fast file transfer program based on TCP sockets