Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.56 KB | None | 0 0
  1. import javax.swing.*;
  2. import java.awt.event.ActionEvent;
  3. import java.awt.event.ActionListener;
  4. import java.io.*;
  5. import java.net.ServerSocket;
  6. import java.net.Socket;
  7. import java.text.SimpleDateFormat;
  8. import java.util.Arrays;
  9. import java.util.Random;
  10.  
  11. public class Peer extends JFrame implements ActionListener {
  12. public int portNumDown;
  13. private BufferedReader in;
  14. private BufferedReader inFromConsole;
  15. private DataOutputStream out;
  16. private String lastFileName;
  17.  
  18. private JButton search; //Buttons
  19. private JButton dload;
  20. private JButton close;
  21.  
  22. private JList jl; // List that will show found files
  23. private JLabel label; //Label "File Name
  24. private JTextField tf, tf2; // Two textfields: one is for typing a file name, the other is just to show the selected file
  25. DefaultListModel<String> listModel; // Used to select items in the list of found files
  26.  
  27. /**
  28. * Connects to the server then enters the processing loop.
  29. */
  30. private void runLogin() {
  31. // Make connection and initialize streams
  32. Socket socket = null;
  33. portNumDown = 3334;
  34. try {
  35. socket = new Socket("192.168.1.20", 3333);
  36. } catch (IOException e) {
  37. e.printStackTrace();
  38. JOptionPane.showMessageDialog(null, "Cannot connect to the file tracker. Check the Internet connection", "File Tracker", JOptionPane.PLAIN_MESSAGE);
  39. return;
  40. }
  41.  
  42. try {
  43. in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  44. inFromConsole = new BufferedReader(new InputStreamReader(System.in));
  45. out = new DataOutputStream(socket.getOutputStream());
  46. } catch (IOException e) {
  47. e.printStackTrace();
  48. }
  49.  
  50. String rsp = "";
  51. try {
  52. out.writeBytes("HELLO\r\n");
  53. out.flush();
  54. String msg = in.readLine();
  55. if (msg.equals("HI")) {
  56. SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
  57. File folder = new File(System.getProperty("user.dir") + System.getProperty("file.separator") + "shared");
  58. File[] listOfFiles = folder.listFiles();
  59. if (listOfFiles != null) {
  60. int tmp = 0;
  61. for (File file : listOfFiles) {
  62. if (file.isFile()) {
  63. if (tmp != 0) {
  64. rsp += "|";
  65. }
  66. rsp += file.getName().substring(0, file.getName().lastIndexOf("."))
  67. + ","
  68. + file.getName().substring(file.getName().lastIndexOf(".") + 1)
  69. + ","
  70. + file.length()
  71. + ","
  72. + sdf.format(file.lastModified())
  73. + ","
  74. + portNumDown;
  75. tmp++;
  76. }
  77. }
  78. }
  79. out.writeBytes(rsp + "\r\n");
  80. out.flush();
  81. msg = in.readLine();
  82. if (msg.equals("NOT ACCEPTED")) {
  83. JOptionPane.showMessageDialog(null,
  84. "You are not accepted since you share no file. Please create <<shared>> folder with files", "File Tracker", JOptionPane.PLAIN_MESSAGE);
  85. System.out.println("You were not accepted");
  86. System.exit(-1);
  87. } else {
  88. System.out.println("You were accepted");
  89. ThreadSeed ts = null;
  90. try {
  91. ts = new ThreadSeed(portNumDown);
  92. } catch (IOException e) {
  93. e.printStackTrace();
  94. }
  95. ts.start();
  96. }
  97.  
  98. } else {
  99. JOptionPane.showMessageDialog(null, "Cannot connect to the file tracker. Check the Internet connection", "File Tracker", JOptionPane.PLAIN_MESSAGE);
  100. System.out.println("Error on Hi-Hello");
  101. System.exit(-1);
  102. }
  103. } catch (IOException e) {
  104. e.printStackTrace();
  105. }
  106. }
  107.  
  108. void initGUI() {
  109. setLayout(null);
  110. setSize(500, 600);
  111.  
  112. label = new JLabel("File name:");
  113. label.setBounds(50, 50, 80, 20);
  114. add(label);
  115.  
  116. tf = new JTextField();
  117. tf.setBounds(130, 50, 220, 20);
  118. add(tf);
  119.  
  120. search = new JButton("Search");
  121. search.setBounds(360, 50, 80, 20);
  122. search.addActionListener(this);
  123. add(search);
  124.  
  125. listModel = new DefaultListModel<>();
  126. jl = new JList<>(listModel);
  127.  
  128. JScrollPane listScroller = new JScrollPane(jl);
  129. listScroller.setBounds(50, 80, 300, 300);
  130.  
  131. add(listScroller);
  132.  
  133. dload = new JButton("Download");
  134. dload.setBounds(200, 400, 130, 20);
  135. dload.addActionListener(this);
  136. add(dload);
  137.  
  138. tf2 = new JTextField();
  139. tf2.setBounds(200, 430, 130, 20);
  140. add(tf2);
  141.  
  142. close = new JButton("Close");
  143. close.setBounds(360, 470, 80, 20);
  144. close.addActionListener(this);
  145. add(close);
  146. setVisible(true);
  147. }
  148.  
  149. public static void main(String[] args) throws Exception {
  150. Peer client = new Peer();
  151. client.runLogin();
  152. client.initGUI();
  153. client.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close the window if x button is pressed
  154. }
  155.  
  156. @Override
  157. public void actionPerformed(ActionEvent e) {
  158. if (e.getSource() == search) { //If search button is pressed show 25 randomly generated file info in text area
  159. ThreadSearch ts = new ThreadSearch();
  160. ts.start();
  161.  
  162. // String rsp = tf.getText();
  163. // try {
  164. // out.writeBytes("SEARCH: " + rsp + "\r\n");
  165. // out.flush();
  166. // lastFileName = rsp;
  167. // rsp = in.readLine();
  168. // String[] elems = rsp.split("->");
  169. // listModel.removeAllElements();
  170. // if (elems[0].substring(0, 5).equals("FOUND")) {
  171. // tf2.setText("");
  172. // for (int i = 0; i < elems.length; ++i) {
  173. // if (i == 0) listModel.insertElementAt(elems[0].substring(7), 0);
  174. // else listModel.insertElementAt(elems[i], i);
  175. // }
  176. // } else {
  177. // tf2.setText("NOT FOUND");
  178. // }
  179. // System.out.println(rsp);
  180. // } catch (IOException e1) {
  181. // e1.printStackTrace();
  182. // }
  183. } else if (e.getSource() == dload) { //If download button is pressed get the selected value from the list and show it in text field
  184. ThreadHandler th = new ThreadHandler();
  185. th.start();
  186. } else if(e.getSource() == close){ //If close button is pressed exit
  187. try {
  188. out.writeBytes("BYE\r\n");
  189. out.flush();
  190. } catch (IOException e1) {
  191. e1.printStackTrace();
  192. }
  193.  
  194. System.exit(0);
  195. }
  196. }
  197.  
  198. class ThreadSearch extends Thread {
  199. private Thread t = null;
  200.  
  201. public void run() {
  202. String rsp = tf.getText();
  203. try {
  204.  
  205. out.writeBytes("SEARCH: " + rsp + "\r\n");
  206. out.flush();
  207. lastFileName = rsp;
  208. rsp = in.readLine();
  209. System.out.println("TEXT" + rsp);
  210.  
  211. String[] elems = rsp.split("->");
  212. listModel.removeAllElements();
  213. if (elems[0].substring(0, 5).equals("FOUND")) {
  214. tf2.setText("");
  215. for (int i = 0; i < elems.length; ++i) {
  216. if (i == 0) listModel.insertElementAt(elems[0].substring(7), 0);
  217. else listModel.insertElementAt(elems[i], i);
  218. }
  219. } else {
  220. tf2.setText("NOT FOUND");
  221. }
  222. System.out.println(rsp);
  223. } catch (IOException e1) {
  224. e1.printStackTrace();
  225. }
  226.  
  227. }
  228.  
  229. public void start() {
  230. if (t == null) {
  231. t = new Thread(this);
  232. t.start();
  233. }
  234. }
  235.  
  236.  
  237.  
  238.  
  239.  
  240.  
  241.  
  242. }
  243.  
  244. class ThreadSeed extends Thread {
  245. private Thread t = null;
  246. private ServerSocket socket;
  247. private boolean isServerOn = true;
  248.  
  249. public ThreadSeed(int port) throws IOException {
  250. try {
  251. socket = new ServerSocket(port);
  252. } catch (IOException ioe) {
  253. System.out.println("Cannot create server socket on port 3334...");
  254. System.exit(-1);
  255. }
  256. }
  257.  
  258. public void run() {
  259. while (isServerOn) {
  260. try {
  261. Socket seedSock = socket.accept();
  262. System.out.println("SOMEBODY TO DOWNLOAD ARRIVED");
  263. SeedHandler seedThread = new SeedHandler(seedSock);
  264. seedThread.start();
  265. } catch (IOException ioe) {
  266. System.out.println("Exception on accepting");
  267. ioe.printStackTrace();
  268. }
  269. }
  270.  
  271. try {
  272. socket.close();
  273. System.out.println("Peer stopped accepting seeds");
  274. } catch (IOException ioe) {
  275. System.out.println("Error found on closing server socket");
  276. System.exit(-1);
  277. }
  278. }
  279.  
  280. public void start() {
  281. if (t == null) {
  282. t = new Thread(this);
  283. t.start();
  284. }
  285. }
  286. }
  287.  
  288. class SeedHandler extends Thread {
  289. private Thread t = null;
  290. private BufferedReader in;
  291. private DataOutputStream out;
  292. private Socket socket;
  293.  
  294. public SeedHandler(Socket sock) throws IOException {
  295. this.socket = sock;
  296. this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  297. this.out = new DataOutputStream(socket.getOutputStream());
  298. }
  299.  
  300. public void run() {
  301. String req = "";
  302.  
  303. try {
  304. req = in.readLine();
  305. req = req.split(":")[1].substring(1);
  306. String[] attrs = req.split(",");
  307. File folder = new File(System.getProperty("user.dir") + System.getProperty("file.separator") + "shared");
  308. File[] listOfFiles = folder.listFiles();
  309. if (listOfFiles != null) {
  310. for (File file : listOfFiles) {
  311. if (file.isFile()
  312. && file.getName().substring(0, file.getName().lastIndexOf(".")).equals(attrs[0])
  313. && file.length() == Integer.parseInt(attrs[2].substring(1))
  314. && file.getName().substring(file.getName().lastIndexOf(".") + 1).equals(attrs[1].substring(1))) {
  315.  
  316. Random rand = new Random();
  317. int value = rand.nextInt(100);
  318. System.out.println("rand is " + value);
  319. if (value < 50) {
  320. System.out.println("SENDIND THE FILE");
  321. byte[] mybytearray = new byte[(int) file.length()];
  322. FileInputStream fis = new FileInputStream(file);
  323. fis.read(mybytearray);
  324. out.writeBytes("FILE: ");
  325. out.write(mybytearray);
  326. out.writeBytes("\r\n");
  327. out.flush();
  328. fis.close();
  329. } else {
  330. out.writeBytes("NO!\r\n");
  331. out.flush();
  332. }
  333. }
  334. }
  335. }
  336.  
  337. } catch (IOException e) {
  338. e.printStackTrace();
  339. } finally {
  340. try {
  341. in.close();
  342. out.close();
  343. socket.close();
  344. } catch (IOException ioe) {
  345. ioe.printStackTrace();
  346. }
  347. }
  348.  
  349.  
  350. }
  351.  
  352. public void start() {
  353. if (t == null) {
  354. t = new Thread(this);
  355. t.start();
  356. }
  357. }
  358. }
  359.  
  360.  
  361. class ThreadHandler extends Thread {
  362. private Thread t = null;
  363.  
  364. public void run() {
  365. if (!jl.isSelectionEmpty()) {
  366. String rsp = "";
  367.  
  368. String param = jl.getSelectedValue().toString();
  369. String[] params = param.split(",");
  370. String[] inet = params[3].split(":");
  371. String ip = inet[0].substring(1);
  372. int port = Integer.parseInt(inet[1]);
  373.  
  374. try {
  375. Socket downSocket = new Socket(ip, port);
  376. String attr = "DOWNLOAD: " + lastFileName + ", " + params[0] + "," + params[1] + "\r\n";
  377. DataOutputStream out1 = new DataOutputStream(downSocket.getOutputStream());
  378. out1.writeBytes(attr);
  379. out1.flush();
  380. InputStream is = downSocket.getInputStream();
  381. OutputStream os = null;
  382.  
  383. byte[] bytes = new byte[16 * 1024];
  384. int count;
  385. String tmp = "";
  386. boolean isEntered = true;
  387. int off = 0;
  388. boolean isValid = false;
  389. do {
  390. count = is.read(bytes, off, 6 - off);
  391. System.out.println("count=" + count);
  392. String b = new String(bytes);
  393. System.out.println("arrray: " + b);
  394. off += count;
  395. } while (count != -1 && off < 6);
  396. count = off;
  397. do {
  398. if (isEntered) {
  399. tmp = new String(bytes);
  400. System.out.println(tmp.substring(0, 4) + count);
  401. if (tmp.substring(0, 3).equals("NO!")) {
  402. isValid = false;
  403. break;
  404. }
  405. if (tmp.substring(0, 4).equals("FILE")) {
  406. System.out.println("IMGERE");
  407. isValid = true;
  408. os = new FileOutputStream(System.getProperty("user.dir")
  409. + System.getProperty("file.separator") + "downloaded" + System.getProperty("file.separator")
  410. + lastFileName + "." + params[0]);
  411. os.write(bytes, 6, count - 6);
  412. os.flush();
  413. }
  414. isEntered = false;
  415. } else {
  416. os.write(bytes, 0, count);
  417. os.flush();
  418. }
  419. } while ((count = is.read(bytes)) > 0);
  420. is.close();
  421. if (isValid) {
  422. out.writeBytes("SCORE:" + ip + ":" + port + ":1\r\n");
  423. out.flush();
  424. os.close();
  425. tf2.setText("FILE DOWNLOADED");
  426. } else {
  427. out.writeBytes("SCORE:" + ip + ":" + port + ":0\r\n");
  428. out.flush();
  429. tf2.setText("FAILED TO DOWNLOAD");
  430. }
  431. out1.close();
  432. downSocket.close();
  433. } catch (IOException e) {
  434. e.printStackTrace();
  435. }
  436. }
  437.  
  438. }
  439.  
  440. public void start() {
  441. if (t == null) {
  442. t = new Thread(this);
  443. t.start();
  444. }
  445. }
  446. }
  447.  
  448.  
  449. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement