Advertisement
Guest User

Untitled

a guest
Dec 28th, 2017
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 15.62 KB | None | 0 0
  1. /////ClientHandler
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.BufferedWriter;
  5. import java.io.File;
  6. import java.io.FileReader;
  7. import java.io.FileWriter;
  8. import java.io.IOException;
  9. import java.io.InputStreamReader;
  10. import java.io.PrintStream;
  11. import java.io.PrintWriter;
  12. import java.net.Socket;
  13.  
  14. public class ClientHandler extends Thread {
  15.    
  16.         private BufferedReader clientInput = null;
  17.         private PrintStream clientOutput = null;
  18.         private Socket soketZaKomunikaciju;
  19.         private String username;
  20.         private Boolean uploadUtoku = false;
  21.         private Boolean fileNameInput = false;
  22.         Korisnik korisnik = null;
  23.         String password;
  24.         String opcija;
  25.         boolean isLoggedIn = false;
  26.         String message;
  27.         String fileName;
  28.         boolean isValid = false;
  29.         PrintWriter printWriter = null;
  30.     File f;
  31.     public ClientHandler(Socket soket) {
  32.         soketZaKomunikaciju = soket;
  33.     }
  34.    
  35.      private static String generisiImeFajla(int count) {
  36.             String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
  37.                                           "abcdefghijklmnopqrstuvwxyz" +
  38.                                           "0123456789";
  39.             StringBuilder builder = new StringBuilder();
  40.             while (count-- != 0) {
  41.                 int character = (int)(Math.random()*ALPHA_NUMERIC_STRING.length());
  42.                 builder.append(ALPHA_NUMERIC_STRING.charAt(character));
  43.             }
  44.             return builder.toString();
  45.         }
  46.    
  47.    
  48.      @Override
  49.         public void run() {
  50.            
  51.             try {
  52.                
  53.  
  54.                 clientInput = new BufferedReader(new InputStreamReader(soketZaKomunikaciju.getInputStream()));
  55.                 clientOutput = new PrintStream(soketZaKomunikaciju.getOutputStream());
  56.  
  57.                
  58.                
  59.  
  60.                 do {
  61.                          clientOutput.println("===========================================================");
  62.                          clientOutput.println("Izaberite opciju:");
  63.                          clientOutput.println("1. Registruj se.");
  64.                          clientOutput.println("2. Prijavi se.");
  65.                          clientOutput.println("0. Kraj");
  66.                          clientOutput.println("===========================================================");
  67.  
  68.                          message = clientInput.readLine();
  69.                          
  70.                          
  71.                          if (message.equals("1")) {
  72.                              clientOutput.println("Unestite korisnicko ime:");
  73.                              username = clientInput.readLine();
  74.                              
  75.                              clientOutput.println("Unesite vasu lozinku");
  76.                              password = clientInput.readLine();
  77.                              
  78.                              if (Server.registrujNovogKorisnika(username, password)) {
  79.                                  clientOutput.println("Uspesno ste se registrovali. Mozete se ulogovati sa unetim kredencijalima");
  80.                                  
  81.                                
  82.                                  
  83.                                  
  84.                                  } else {
  85.                                  clientOutput.println("Korisnicko ime " + username + " je vec registrovano");
  86.                              }
  87.                          } else if (message.equals("2")) {
  88.                              clientOutput.println("Unestite korisnicko ime:");
  89.                              username = clientInput.readLine();
  90.                              
  91.                              clientOutput.println("Unesite vasu lozinku");
  92.                              password = clientInput.readLine();
  93.                              
  94.                              if (Server.prijaviKorisnika(username, password)) {
  95.                                  clientOutput.println("DOBRODOSLI! Uspesno ste se prijavili na sistem");
  96.                                  isLoggedIn = true;
  97.                                  korisnik = Server.dohvatiKorisnika(username, password);
  98.                              } else {
  99.                                  clientOutput.println("Uneti kredencijali su neispravni");
  100.                              }
  101.                          
  102.                          } else if (message.equals("0")) {
  103.                             clientOutput.println("Dovidjenja");
  104.                              break;
  105.                          } else {
  106.                              clientOutput.println("Uneta nepostojeca opcija");
  107.                          }
  108.                      
  109.                      
  110.                      
  111.                
  112.                  
  113.                    
  114.                    
  115.                          if(isLoggedIn) {
  116.                        
  117.                    
  118.                         isValid = true;
  119.                         clientOutput.println(">>> Dobrodosli " +username);
  120.                         clientOutput.println("A. Za upload unesite ***up");
  121.                         clientOutput.println("   Za prekid uploada unesite ***eof");
  122.                         clientOutput.println("B. Za download unesite ***dn");
  123.                         clientOutput.println("C. Za izlazak unesite ***quit");}
  124.                    
  125.                 }while(!isValid);
  126.                
  127.                 // Ovde je definisano primanje poruka od korisnika
  128.  
  129.                
  130.                
  131.                 while(true) {
  132.  
  133.                     message = clientInput.readLine();
  134.  
  135.                     // ako poruka sadrzi niz karaktera koji ukazuju na izlaz, izlazi se iz petlje, korisnik se izbacuje
  136.                     // iz liste  usera na serveru
  137.  
  138.                     if (message.startsWith("***quit")) {
  139.                         break;
  140.                     } else if (message.startsWith("***up")) {  // kreiram fajl
  141.                         System.out.println("Krece upload");
  142.                         fileName = generisiImeFajla(10);
  143.                         clientOutput.println("Ime fajla je: " + fileName);
  144.                         uploadUtoku = true;
  145.                         FileWriter fileWriter = new FileWriter(fileName);
  146.                         printWriter = new PrintWriter(fileWriter);
  147.                     } else if (message.startsWith("***eof")) {  // zatvaram fajl
  148.                        
  149.                        
  150.                         if (message.length() > 500) {
  151.                             clientOutput.println("Maksimalna velicina fajla je 500 karaktera.");
  152.                             } else {
  153.                         System.out.println("Upload zavrsen");
  154.                         uploadUtoku = false;
  155.                         printWriter.flush();
  156.                         printWriter.close();
  157.                         clientOutput.println("Fajl " + fileName + " je uspesno snimljen");
  158.                         fileName = null;
  159.                         }
  160.                     } else if (message.startsWith("***dn")) {  // upisujem u fajl
  161.                         System.out.println("Krece download");
  162.                         clientOutput.println("Unesite ime fajla: ");
  163.                         fileNameInput = true;
  164.                     } else {
  165.                         if (uploadUtoku) {
  166.                             printWriter.println(message);
  167.                         } else if (fileNameInput) {
  168.                             fileName = message;
  169.                             clientOutput.println("Trazim fajl: " + fileName);
  170.                             fileNameInput = false;
  171.                             //File file = new File(fileName);
  172.                             if (new File(fileName).exists()) {
  173.                                 clientOutput.println("Pronadjen fajl: " + fileName);
  174.                                 // Ako nadjem fajl pocinjem slanje
  175.                                 clientOutput.println("---BOF---");
  176.                                 clientOutput.println(fileName);
  177.                                 BufferedReader br = null;
  178.                                 try{
  179.                                     br = new BufferedReader(new FileReader(fileName));
  180.  
  181.                                    
  182.                                     String contentLine = br.readLine();
  183.                                     while (contentLine != null) {
  184.                                         clientOutput.println(contentLine);
  185.                                         contentLine = br.readLine();
  186.                                     }
  187.                                 }
  188.                                 catch (IOException ioe)
  189.                                 {
  190.                                     ioe.printStackTrace();
  191.                                 }
  192.                                 finally
  193.                                 {
  194.                                     try {
  195.                                         if (br != null)
  196.                                             br.close();
  197.                                     }
  198.                                     catch (IOException ioe)
  199.                                     {
  200.                                         ioe.printStackTrace();
  201.                                     }
  202.                                 }
  203.                                 clientOutput.println("---EOF---");
  204.                                
  205.                             } else {
  206.                                 clientOutput.println("NIJE pronadjen fajl: " + fileName);
  207.                             }
  208.                         } else {
  209.                             System.out.println("[" + username + "]: " + message);
  210.                         }
  211.                     }
  212.                    
  213.                    
  214.                 }
  215.  
  216.                
  217.                 clientOutput.println(">>> Dovidjenja " +username);
  218.  
  219.  
  220.  
  221.  
  222.  
  223.                
  224.  
  225.                 soketZaKomunikaciju.close();
  226.  
  227.                 // Ovde je obradjen izuzetak u slucaju da korisnik nasilno napusti chat. U smislu da ne otkuca ***quit nego da samo ugasi
  228.                 // klijentsku aplikaciju. Ili da mu nestane struje npr.
  229.  
  230.             }
  231.              catch (Exception e) {
  232.                
  233.             }
  234.         }
  235.  
  236.     }
  237. ///////////////////// KLASA Korisnik
  238. /*
  239.  * To change this license header, choose License Headers in Project Properties.
  240.  * To change this template file, choose Tools | Templates
  241.  * and open the template in the editor.
  242.  */
  243.  
  244.  
  245. import java.util.HashMap;
  246.  
  247.  
  248. public class Korisnik {
  249.     private String username;
  250.     private String password;
  251.     private HashMap<String, String> files;
  252.  
  253.     public Korisnik(String username, String password) {
  254.         this.username = username;
  255.         this.password = password;
  256.         this.files = new HashMap<>();
  257.     }
  258.    
  259.     public boolean dodajNoviFajl(String kodFajla, String sadrzajFajla) {
  260.         if (files.containsKey(kodFajla)) {
  261.             return false;
  262.         }
  263.        
  264.         files.put(kodFajla, sadrzajFajla);
  265.         return true;
  266.     }
  267.  
  268.     public String dohvatiFajl(String kodFajla) {
  269.         if (files.containsKey(kodFajla)) {
  270.             return files.get(kodFajla);
  271.         }
  272.        
  273.         return null;
  274.     }
  275.    
  276.     public String getUsername() {
  277.         return username;
  278.     }
  279.  
  280.     public void setUsername(String username) {
  281.         this.username = username;
  282.     }
  283.  
  284.     public String getPassword() {
  285.         return password;
  286.     }
  287.  
  288.     public void setPassword(String password) {
  289.         this.password = password;
  290.     }
  291.  
  292.    
  293.  
  294.    
  295.    
  296.    
  297. }
  298. /////////////// Server
  299.  
  300.  
  301.  
  302. import java.io.BufferedWriter;
  303. import java.io.File;
  304. import java.io.FileWriter;
  305. import java.io.IOException;
  306. import java.net.ServerSocket;
  307. import java.net.Socket;
  308. import java.nio.file.FileSystems;
  309. import java.nio.file.Files;
  310. import java.nio.file.Path;
  311. import java.util.LinkedList;
  312.  
  313. public class Server {
  314.      public static LinkedList<Korisnik> registrovaniKorisnici = new LinkedList<>();
  315.    
  316.      public static Korisnik dohvatiKorisnika(String username, String password) {
  317.             for (Korisnik korisnik : registrovaniKorisnici) {
  318.                 if (korisnik.getUsername().equals(username)) {
  319.                     if (korisnik.getPassword().equals(password)) {
  320.                         return korisnik;
  321.                     }
  322.                 }
  323.             }
  324.            
  325.             return null;
  326.         }
  327.        
  328.      
  329.         public static boolean registrujNovogKorisnika(String username, String password) {
  330.            
  331.             for (Korisnik korisnik : registrovaniKorisnici) {
  332.                 if (korisnik.getUsername().equals(username)) {
  333.                     return false;
  334.                 }
  335.             }
  336.            
  337.             Korisnik kor = new Korisnik(username, password);
  338.             registrovaniKorisnici.add(kor);
  339.            
  340.             return true;
  341.         }
  342.         /*
  343.             Prijavljivanje korisnika na server.
  344.        
  345.             Proverava unetog korisnickog imena i lozinke.
  346.             Rezultat metode je uspesnost prijavljivanje.
  347.        
  348.         */
  349.         public static boolean prijaviKorisnika(String username, String password) {
  350.             for (Korisnik korisnik : registrovaniKorisnici) {
  351.                 if (korisnik.getUsername().equals(username)) {
  352.                     if (korisnik.getPassword().equals(password)) {
  353.                         return true;
  354.                     }
  355.                 }
  356.             }
  357.            
  358.             return false;
  359.         }
  360.        
  361.  
  362.     public static void main(String[] args) {
  363.        
  364.        
  365.    
  366.         int port = 5555;
  367.         ServerSocket serverSoket;
  368.         Socket soketZaKomunikaciju;
  369.        
  370.         try {
  371.              
  372.        
  373.             serverSoket = new ServerSocket(port);
  374.            
  375.        
  376.            
  377.             while (true) {
  378.                
  379.                 System.out.println("Cekam na konekciju...");
  380.                 soketZaKomunikaciju = serverSoket.accept();
  381.                 System.out.println("Doslo je do konekcije!");
  382.                
  383.                 ClientHandler klijent = new ClientHandler(soketZaKomunikaciju);
  384.                
  385.                
  386.              
  387.                
  388.  
  389.                
  390.  
  391.                 klijent.start();
  392.             }
  393.         } catch (IOException e) {
  394.              System.out.println("Greska prilikom pokretanja servera!");
  395.         }
  396.     }
  397.  
  398. }
  399. ///////////////////Client
  400.  
  401. import java.io.BufferedReader;
  402. import java.io.IOException;
  403. import java.io.InputStreamReader;
  404. import java.io.PrintStream;
  405. import java.net.Socket;
  406. import java.net.UnknownHostException;
  407.  
  408. public class Client implements Runnable{
  409.    
  410.    
  411.     static private PrintStream serverOutput = null;
  412.     static private BufferedReader unosSaTastature = null;
  413.        
  414.  
  415.     public static void main(String[] args) {
  416.        
  417.         try {
  418.              
  419.  
  420.             Socket soketZaKomunikaciju = new Socket("localhost", 5555);
  421.  
  422.            
  423.  
  424.             BufferedReader serverInput = new BufferedReader(new InputStreamReader(soketZaKomunikaciju.getInputStream()));
  425.             serverOutput = new PrintStream(soketZaKomunikaciju.getOutputStream());
  426.  
  427.             unosSaTastature = new BufferedReader(new InputStreamReader(System.in));
  428.  
  429.            
  430.            
  431.             new Thread(new Client()).start();
  432.            
  433.             String input;
  434.            
  435.          // Dokle god stizu poruke, iste se ispisuju na strani klijenta
  436.             // Ako dodje poruka koja pocinje sa >>> Dovidjenja, a to je u slucaju da smo mi uneli ***quit, zatvara se
  437.             // soket za komunikaciju
  438.  
  439.             while(true) {
  440.                 input = serverInput.readLine();
  441.                 System.out.println(input);
  442.  
  443.                 if(input.startsWith(">>> Dovidjenja")) {
  444.                     break;
  445.                 }
  446.             }
  447.            
  448.          // Zatvaranje soketa u slucaju kada napustamo
  449.  
  450.             soketZaKomunikaciju.close();
  451.  
  452.            
  453.         } catch (UnknownHostException e) {
  454.             System.out.println("UNKNOWN HOST!");
  455.            
  456.         }catch (IOException e) {
  457.             System.out.println("SERVER IS DOWN!!!");
  458.         }
  459.        
  460.  
  461.     }
  462.  
  463.     @Override
  464.     public void run() {
  465.           try {
  466.  
  467.                 String message;
  468.  
  469.                 while(true) {
  470.  
  471.                     message = unosSaTastature.readLine();
  472.                     serverOutput.println(message);
  473.  
  474.                  
  475.  
  476.                     if(message.equals("***quit")) {
  477.                         break;
  478.                     }
  479.                 }
  480.  
  481.             } catch (IOException e) {
  482.                
  483.                 e.printStackTrace();
  484.             }
  485.        
  486.     }
  487.  
  488. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement