Advertisement
Guest User

Scala Client/Server

a guest
May 29th, 2016
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 9.59 KB | None | 0 0
  1. //SERVER
  2. import java.net._
  3. import java.io._
  4. import scala.io._
  5. import scala.util.control._
  6. import java.lang.String
  7. import collection.mutable.HashMap
  8.  
  9. object HelloServerWorld {
  10.   class ScalaServer(val _conn: Socket, _root:String) extends Runnable {
  11.     val CONN = _conn
  12.     var root:String = _root
  13.     val in = new DataInputStream(CONN.getInputStream())
  14.     val out = new DataOutputStream(CONN.getOutputStream())
  15.  
  16.     def getListOfFiles(dir: String):List[File] = {
  17.       val d = new File(dir)
  18.       if (d.exists && d.isDirectory) {
  19.         d.listFiles.filter(_.isFile).toList
  20.       } else {
  21.       List[File]()
  22.       }
  23.     }
  24.  
  25.     def Pwd() : Unit = {
  26.         var dir:String = '\t'+System.getProperty("user.dir")
  27.         out.writeUTF("\n"+dir)
  28.         out.flush()
  29.     }
  30.  
  31.     def ls() : Unit = {
  32.         val Currdir = System.getProperty("user.dir")
  33.         val files = getListOfFiles(Currdir)
  34.         var dirs :String = "\n"
  35.         for ( i <- 0 to (files.length - 1)) {
  36.           dirs += '\t'+files(i).getName()+'\n'
  37.         }
  38.         out.writeUTF(dirs)
  39.         out.flush()
  40.     }
  41.  
  42.     def cd() : Unit = {
  43.       val outer = new Breaks
  44.       outer.breakable {
  45.         while(true)
  46.         {
  47.           out.writeUTF("Insert absolute path of the directory that you want to navigate to: ")
  48.             out.flush()
  49.             var dir :String = in.readUTF()
  50.             var CurrentDir:String = System.getProperty("user.dir")
  51.             var dirToBE:String = root.replace('\\','/')
  52.             println(dir)
  53.             System.setProperty("user.dir", dirToBE+"/"+dir)
  54.             println(System.getProperty("user.dir"))
  55.             out.writeUTF("Current directory is: "+System.getProperty("user.dir"))
  56.             out.flush()
  57.             outer.break
  58.         }
  59.       }
  60.     }
  61.  
  62.     def saveFile() : Unit = {
  63.     out.writeUTF("Input file path")
  64.     out.flush()
  65.     val archivoName = in.readUTF()
  66.     val tam = in.readUTF()
  67.     if(archivoName != "File does not exists"){
  68.         val fos = new FileOutputStream(archivoName)
  69.         var bytes = new Array[Byte](1024)
  70.         var bytesLeidos:Int = 0
  71.         var tama:Int = Integer.parseInt(tam)
  72.         println(tama)
  73.         while(tama > 0) {
  74.             if(tama <= 1024){
  75.                 bytesLeidos = in.read(bytes, 0, tama)
  76.             } else{
  77.                 bytesLeidos = in.read(bytes, 0, 1024)
  78.             }
  79.             tama -= bytesLeidos
  80.             fos.write(bytes, 0, bytesLeidos)
  81.         }
  82.         fos.close()
  83.         out.writeUTF("Received successfully")
  84.         out.flush()
  85.     }else {
  86.         out.writeUTF("File does not exists")
  87.         out.flush()
  88.     }
  89. }
  90.  
  91.     def mkdir() : Unit = {
  92.     out.writeUTF("Name of new directory: ")
  93.     out.flush()
  94.     val _dirName = in.readUTF()
  95.     val mkDir = new File(System.getProperty("user.dir") + "/" + _dirName)
  96.     val successful = mkDir.mkdir();
  97.     if(successful) {
  98.         out.writeUTF("Directory successfully created")
  99.     }else {
  100.         out.writeUTF("Unable to create directory")
  101.     }
  102.     out.flush()
  103.   }
  104.  
  105. def rm() : Unit = {
  106.     out.writeUTF("Name of file/directory to delete: ")
  107.     out.flush()
  108.     val delPath = in.readUTF()
  109.     val rm = new File(System.getProperty("user.dir") + "/" + delPath)
  110.     if(rm.exists) {
  111.         rm.delete()
  112.         out.writeUTF("Deleted successfully")
  113.     }else {
  114.         out.writeUTF("Unable to delete")
  115.     }
  116.     out.flush()
  117. }
  118.  
  119. def sendFile() : Unit = {
  120.     out.writeUTF("File to download")
  121.     out.flush()
  122.     val estoQuiero = in.readUTF()
  123.     val archivo = new File(estoQuiero)
  124.     if(archivo.exists){
  125.         out.writeUTF(archivo.length.toString())
  126.         out.flush()
  127.         val fos = out
  128.         val leer = new FileInputStream(estoQuiero);
  129.         var bytes = new Array[Byte](1024);
  130.         var tama:Int = archivo.length.intValue()
  131.         var bytesLeidos:Int = 0
  132.         while(tama > 0) {
  133.             if(tama <= 1024){
  134.                 bytesLeidos = leer.read(bytes, 0, tama)
  135.             } else{
  136.                 bytesLeidos = leer.read(bytes, 0, 1024)
  137.             }
  138.             tama -= bytesLeidos
  139.             fos.write(bytes, 0, bytesLeidos)
  140.         }
  141.         leer.close();
  142.         out.writeUTF("File sent successfully")
  143.         out.flush()
  144.     }else{
  145.         out.writeUTF("File does not exists")
  146.         out.flush()
  147.     }
  148. }
  149.  
  150. def userHandler(user: String, password: String) : Boolean = {
  151.     var usuarios = HashMap[String, String]()
  152.     val archivo = new File("users.txt")
  153.     var leido = ""
  154.     if (archivo.exists){
  155.         Source.fromFile("users.txt" ).foreach{case line =>
  156.             leido += line
  157.       }
  158.         var splitUsers: Array[java.lang.String] = leido.split(",").map(_.trim)
  159.         var esUsuario = 0;
  160.         var arrayTam = splitUsers.size
  161.         while(arrayTam > esUsuario){
  162.             usuarios(splitUsers(esUsuario)) = splitUsers(esUsuario+1)
  163.             esUsuario += 2
  164.         }
  165.     }
  166.    
  167.     if(usuarios contains user){
  168.         if(usuarios(user) == password){
  169.             println("Login success")
  170.             return true
  171.         }else{
  172.             println("Contraseña incorrecta")
  173.             return false
  174.         }
  175.     }else {
  176.       out.writeUTF("User does not exist, do you want to create [Y/N]")
  177.       if(in.readUTF()=="Y"){
  178.         usuarios(user) = password
  179.         println("Usuario creado y login success")
  180.         }
  181.     }
  182.    
  183.     val writer = new PrintWriter(new File("users.txt" ))
  184.     var tam = usuarios.size
  185.     var iteracion = 0;
  186.     usuarios.foreach{case(key, value) =>
  187.         writer.write(key)
  188.         writer.write(",")
  189.         writer.write(value)
  190.         if(iteracion != (tam-1)){
  191.             writer.write(",")
  192.         }
  193.         iteracion += 1;
  194.     }
  195.     writer.close()
  196.     return false
  197. }
  198.  
  199.     def logic() : Unit = {
  200.       while(true){
  201.       var login:String = "\n"
  202.       login+="\t"+"--------Login--------"+"\n"
  203.       login+="\t"+"Input you username: "+"\n"
  204.       out.writeUTF(login)
  205.       var userName:String= in.readUTF()
  206.       out.writeUTF("Input you password: ")
  207.       var password:String= in.readUTF()
  208.       System.setProperty("user.dir",root)
  209.       if(userHandler(userName,password)){
  210.       while(true){
  211.         out.writeUTF(" ")
  212.         val received = in.readUTF()
  213.         println("Message Received:" + received)
  214.         if(received == "pwd"){
  215.           Pwd()
  216.         }else if (received == "ls"){
  217.           ls()
  218.         }else if(received == "cd"){
  219.           cd()
  220.         }else if(received == "get"){
  221.           sendFile()
  222.           out.writeUTF("")
  223.         }else if(received == "put"){
  224.           saveFile()
  225.         }else if(received == "rm"){
  226.             rm()
  227.         }else if(received == "mkdir"){
  228.             mkdir()
  229.         }else{
  230.           out.writeUTF('"'+received+'"'+" is not a valid command.")
  231.           out.flush()
  232.         }
  233.       }
  234.       }else{
  235.         out.writeUTF("Acces denied")
  236.         out.flush()
  237.       }
  238.     }
  239.     }
  240.     def run {
  241.       logic()
  242.     }
  243. }
  244.  
  245.   def main(args: Array[String]){
  246.     val server = new ServerSocket(9999)
  247.     val cont = true
  248.     var root:String = System.getProperty("user.dir")
  249.     while (cont) {
  250.         val s = server.accept()
  251.         println(s.getRemoteSocketAddress())
  252.         new Thread(new ScalaServer(s,root)).start
  253.     }
  254.   }
  255. }
  256.  
  257.  
  258. //CLIENT
  259.  
  260. import java.net._
  261. import java.io._
  262. import scala.io._
  263. import scala.util.control._
  264.  
  265.   def sendFile() : Unit = {
  266.     val mensaje2 = in.readUTF()
  267.     println("Received: " + mensaje2)
  268.     val text2 =  StdIn.readLine()
  269.     val archivo = new File(text2)
  270.     if(archivo.exists){
  271.         out.writeUTF(archivo.getName())
  272.         out.flush()
  273.         out.writeUTF(archivo.length.toString())
  274.         out.flush()
  275.         val leer = new FileInputStream(text2);
  276.         var bytes = new Array[Byte](1024);
  277.         var tama:Int = archivo.length.intValue()
  278.         var bytesLeidos:Int = 0
  279.         while(tama > 0) {
  280.             if(tama <= 1024){
  281.                 bytesLeidos = leer.read(bytes, 0, tama)
  282.             } else{
  283.                 bytesLeidos = leer.read(bytes, 0, 1024)
  284.             }
  285.             tama -= bytesLeidos
  286.             out.write(bytes, 0, bytesLeidos)
  287.         }
  288.         leer.close();
  289.     }else{
  290.         out.writeUTF("No existe")
  291.         out.flush()
  292.         out.writeUTF(0+"")
  293.         out.flush()
  294.     }
  295. }
  296.  
  297. def getFile() : Unit = {
  298.     val mensaje2 = in.readUTF()
  299.     println("Received: " + mensaje2)
  300.     val estoQuiero =  StdIn.readLine()
  301.     out.writeUTF(estoQuiero)
  302.     out.flush()
  303.     val mensaje3 = in.readUTF()
  304.     if(mensaje3 != "File does not exists"){
  305.         println("receiving file")
  306.         //val tam = Integer.parseInt(mensaje3)
  307.         val fos = new FileOutputStream(estoQuiero)
  308.         var bytes = new Array[Byte](1024)
  309.         var bytesLeidos:Int = 0
  310.         var tama:Int = Integer.parseInt(mensaje3)
  311.         while(tama > 0) {
  312.             if(tama <= 1024){
  313.                 bytesLeidos = in.read(bytes, 0, tama)
  314.             } else{
  315.                 bytesLeidos = in.read(bytes, 0, 1024)
  316.             }
  317.             tama -= bytesLeidos
  318.             fos.write(bytes, 0, bytesLeidos)
  319.         }
  320.         fos.close()
  321.         val mensaje4 = in.readUTF()
  322.         println("Received: " + mensaje4)
  323.     }else{
  324.         println("Received: " + mensaje3)
  325.     }
  326. }
  327.  
  328.  
  329. val s = new Socket(InetAddress.getByName("localhost"), 9999)
  330. lazy val in = new DataInputStream(s.getInputStream())
  331. val out = new DataOutputStream(s.getOutputStream())
  332.  
  333. while (true) {
  334.     println("Message from server: " + in.readUTF())
  335.     println("Text to send: ")
  336.     val text = StdIn.readLine()
  337.     out.writeUTF(text)
  338.     out.flush()
  339.     if(text=="put")
  340.     {
  341.         sendFile()
  342.     }else if(text == "get")
  343.     {
  344.         getFile()
  345.     }
  346.     //s.close()
  347. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement