Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.*;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.io.*;
- import java.net.ServerSocket;
- import java.net.Socket;
- import java.text.SimpleDateFormat;
- import java.util.Arrays;
- import java.util.Random;
- public class Peer extends JFrame implements ActionListener {
- public int portNumDown;
- private BufferedReader in;
- private BufferedReader inFromConsole;
- private DataOutputStream out;
- private String lastFileName;
- private JButton search; //Buttons
- private JButton dload;
- private JButton close;
- private JList jl; // List that will show found files
- private JLabel label; //Label "File Name
- private JTextField tf, tf2; // Two textfields: one is for typing a file name, the other is just to show the selected file
- DefaultListModel<String> listModel; // Used to select items in the list of found files
- /**
- * Connects to the server then enters the processing loop.
- */
- private void runLogin() {
- // Make connection and initialize streams
- Socket socket = null;
- portNumDown = 3334;
- try {
- socket = new Socket("192.168.1.20", 3333);
- } catch (IOException e) {
- e.printStackTrace();
- JOptionPane.showMessageDialog(null, "Cannot connect to the file tracker. Check the Internet connection", "File Tracker", JOptionPane.PLAIN_MESSAGE);
- return;
- }
- try {
- in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- inFromConsole = new BufferedReader(new InputStreamReader(System.in));
- out = new DataOutputStream(socket.getOutputStream());
- } catch (IOException e) {
- e.printStackTrace();
- }
- String rsp = "";
- try {
- out.writeBytes("HELLO\r\n");
- out.flush();
- String msg = in.readLine();
- if (msg.equals("HI")) {
- SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
- File folder = new File(System.getProperty("user.dir") + System.getProperty("file.separator") + "shared");
- File[] listOfFiles = folder.listFiles();
- if (listOfFiles != null) {
- int tmp = 0;
- for (File file : listOfFiles) {
- if (file.isFile()) {
- if (tmp != 0) {
- rsp += "|";
- }
- rsp += file.getName().substring(0, file.getName().lastIndexOf("."))
- + ","
- + file.getName().substring(file.getName().lastIndexOf(".") + 1)
- + ","
- + file.length()
- + ","
- + sdf.format(file.lastModified())
- + ","
- + portNumDown;
- tmp++;
- }
- }
- }
- out.writeBytes(rsp + "\r\n");
- out.flush();
- msg = in.readLine();
- if (msg.equals("NOT ACCEPTED")) {
- JOptionPane.showMessageDialog(null,
- "You are not accepted since you share no file. Please create <<shared>> folder with files", "File Tracker", JOptionPane.PLAIN_MESSAGE);
- System.out.println("You were not accepted");
- System.exit(-1);
- } else {
- System.out.println("You were accepted");
- ThreadSeed ts = null;
- try {
- ts = new ThreadSeed(portNumDown);
- } catch (IOException e) {
- e.printStackTrace();
- }
- ts.start();
- }
- } else {
- JOptionPane.showMessageDialog(null, "Cannot connect to the file tracker. Check the Internet connection", "File Tracker", JOptionPane.PLAIN_MESSAGE);
- System.out.println("Error on Hi-Hello");
- System.exit(-1);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- void initGUI() {
- setLayout(null);
- setSize(500, 600);
- label = new JLabel("File name:");
- label.setBounds(50, 50, 80, 20);
- add(label);
- tf = new JTextField();
- tf.setBounds(130, 50, 220, 20);
- add(tf);
- search = new JButton("Search");
- search.setBounds(360, 50, 80, 20);
- search.addActionListener(this);
- add(search);
- listModel = new DefaultListModel<>();
- jl = new JList<>(listModel);
- JScrollPane listScroller = new JScrollPane(jl);
- listScroller.setBounds(50, 80, 300, 300);
- add(listScroller);
- dload = new JButton("Download");
- dload.setBounds(200, 400, 130, 20);
- dload.addActionListener(this);
- add(dload);
- tf2 = new JTextField();
- tf2.setBounds(200, 430, 130, 20);
- add(tf2);
- close = new JButton("Close");
- close.setBounds(360, 470, 80, 20);
- close.addActionListener(this);
- add(close);
- setVisible(true);
- }
- public static void main(String[] args) throws Exception {
- Peer client = new Peer();
- client.runLogin();
- client.initGUI();
- client.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close the window if x button is pressed
- }
- @Override
- public void actionPerformed(ActionEvent e) {
- if (e.getSource() == search) { //If search button is pressed show 25 randomly generated file info in text area
- ThreadSearch ts = new ThreadSearch();
- ts.start();
- // String rsp = tf.getText();
- // try {
- // out.writeBytes("SEARCH: " + rsp + "\r\n");
- // out.flush();
- // lastFileName = rsp;
- // rsp = in.readLine();
- // String[] elems = rsp.split("->");
- // listModel.removeAllElements();
- // if (elems[0].substring(0, 5).equals("FOUND")) {
- // tf2.setText("");
- // for (int i = 0; i < elems.length; ++i) {
- // if (i == 0) listModel.insertElementAt(elems[0].substring(7), 0);
- // else listModel.insertElementAt(elems[i], i);
- // }
- // } else {
- // tf2.setText("NOT FOUND");
- // }
- // System.out.println(rsp);
- // } catch (IOException e1) {
- // e1.printStackTrace();
- // }
- } else if (e.getSource() == dload) { //If download button is pressed get the selected value from the list and show it in text field
- ThreadHandler th = new ThreadHandler();
- th.start();
- } else if(e.getSource() == close){ //If close button is pressed exit
- try {
- out.writeBytes("BYE\r\n");
- out.flush();
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- System.exit(0);
- }
- }
- class ThreadSearch extends Thread {
- private Thread t = null;
- public void run() {
- String rsp = tf.getText();
- try {
- out.writeBytes("SEARCH: " + rsp + "\r\n");
- out.flush();
- lastFileName = rsp;
- rsp = in.readLine();
- System.out.println("TEXT" + rsp);
- String[] elems = rsp.split("->");
- listModel.removeAllElements();
- if (elems[0].substring(0, 5).equals("FOUND")) {
- tf2.setText("");
- for (int i = 0; i < elems.length; ++i) {
- if (i == 0) listModel.insertElementAt(elems[0].substring(7), 0);
- else listModel.insertElementAt(elems[i], i);
- }
- } else {
- tf2.setText("NOT FOUND");
- }
- System.out.println(rsp);
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- }
- public void start() {
- if (t == null) {
- t = new Thread(this);
- t.start();
- }
- }
- }
- class ThreadSeed extends Thread {
- private Thread t = null;
- private ServerSocket socket;
- private boolean isServerOn = true;
- public ThreadSeed(int port) throws IOException {
- try {
- socket = new ServerSocket(port);
- } catch (IOException ioe) {
- System.out.println("Cannot create server socket on port 3334...");
- System.exit(-1);
- }
- }
- public void run() {
- while (isServerOn) {
- try {
- Socket seedSock = socket.accept();
- System.out.println("SOMEBODY TO DOWNLOAD ARRIVED");
- SeedHandler seedThread = new SeedHandler(seedSock);
- seedThread.start();
- } catch (IOException ioe) {
- System.out.println("Exception on accepting");
- ioe.printStackTrace();
- }
- }
- try {
- socket.close();
- System.out.println("Peer stopped accepting seeds");
- } catch (IOException ioe) {
- System.out.println("Error found on closing server socket");
- System.exit(-1);
- }
- }
- public void start() {
- if (t == null) {
- t = new Thread(this);
- t.start();
- }
- }
- }
- class SeedHandler extends Thread {
- private Thread t = null;
- private BufferedReader in;
- private DataOutputStream out;
- private Socket socket;
- public SeedHandler(Socket sock) throws IOException {
- this.socket = sock;
- this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- this.out = new DataOutputStream(socket.getOutputStream());
- }
- public void run() {
- String req = "";
- try {
- req = in.readLine();
- req = req.split(":")[1].substring(1);
- String[] attrs = req.split(",");
- File folder = new File(System.getProperty("user.dir") + System.getProperty("file.separator") + "shared");
- File[] listOfFiles = folder.listFiles();
- if (listOfFiles != null) {
- for (File file : listOfFiles) {
- if (file.isFile()
- && file.getName().substring(0, file.getName().lastIndexOf(".")).equals(attrs[0])
- && file.length() == Integer.parseInt(attrs[2].substring(1))
- && file.getName().substring(file.getName().lastIndexOf(".") + 1).equals(attrs[1].substring(1))) {
- Random rand = new Random();
- int value = rand.nextInt(100);
- System.out.println("rand is " + value);
- if (value < 50) {
- System.out.println("SENDIND THE FILE");
- byte[] mybytearray = new byte[(int) file.length()];
- FileInputStream fis = new FileInputStream(file);
- fis.read(mybytearray);
- out.writeBytes("FILE: ");
- out.write(mybytearray);
- out.writeBytes("\r\n");
- out.flush();
- fis.close();
- } else {
- out.writeBytes("NO!\r\n");
- out.flush();
- }
- }
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- in.close();
- out.close();
- socket.close();
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
- }
- public void start() {
- if (t == null) {
- t = new Thread(this);
- t.start();
- }
- }
- }
- class ThreadHandler extends Thread {
- private Thread t = null;
- public void run() {
- if (!jl.isSelectionEmpty()) {
- String rsp = "";
- String param = jl.getSelectedValue().toString();
- String[] params = param.split(",");
- String[] inet = params[3].split(":");
- String ip = inet[0].substring(1);
- int port = Integer.parseInt(inet[1]);
- try {
- Socket downSocket = new Socket(ip, port);
- String attr = "DOWNLOAD: " + lastFileName + ", " + params[0] + "," + params[1] + "\r\n";
- DataOutputStream out1 = new DataOutputStream(downSocket.getOutputStream());
- out1.writeBytes(attr);
- out1.flush();
- InputStream is = downSocket.getInputStream();
- OutputStream os = null;
- byte[] bytes = new byte[16 * 1024];
- int count;
- String tmp = "";
- boolean isEntered = true;
- int off = 0;
- boolean isValid = false;
- do {
- count = is.read(bytes, off, 6 - off);
- System.out.println("count=" + count);
- String b = new String(bytes);
- System.out.println("arrray: " + b);
- off += count;
- } while (count != -1 && off < 6);
- count = off;
- do {
- if (isEntered) {
- tmp = new String(bytes);
- System.out.println(tmp.substring(0, 4) + count);
- if (tmp.substring(0, 3).equals("NO!")) {
- isValid = false;
- break;
- }
- if (tmp.substring(0, 4).equals("FILE")) {
- System.out.println("IMGERE");
- isValid = true;
- os = new FileOutputStream(System.getProperty("user.dir")
- + System.getProperty("file.separator") + "downloaded" + System.getProperty("file.separator")
- + lastFileName + "." + params[0]);
- os.write(bytes, 6, count - 6);
- os.flush();
- }
- isEntered = false;
- } else {
- os.write(bytes, 0, count);
- os.flush();
- }
- } while ((count = is.read(bytes)) > 0);
- is.close();
- if (isValid) {
- out.writeBytes("SCORE:" + ip + ":" + port + ":1\r\n");
- out.flush();
- os.close();
- tf2.setText("FILE DOWNLOADED");
- } else {
- out.writeBytes("SCORE:" + ip + ":" + port + ":0\r\n");
- out.flush();
- tf2.setText("FAILED TO DOWNLOAD");
- }
- out1.close();
- downSocket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- public void start() {
- if (t == null) {
- t = new Thread(this);
- t.start();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement