Advertisement
Mohammad_Daoud

Peer Writing Thread

Aug 10th, 2021 (edited)
1,009
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.81 KB | None | 0 0
  1. package homeworks.peerApp;
  2.  
  3. /**
  4.  * @TEAM_MEMBERS :
  5.  * MOHAMMAD ABDALLAH RAJA DAOUD - 0173632
  6.  * HAMZA MONTHER MOSTAFA AMIRAH - 0189136
  7.  *
  8.  * @instructor :
  9.  * Dr. Wesam Al Mobaideen
  10.  */
  11.  
  12. import java.io.BufferedReader;
  13. import java.io.DataOutputStream;
  14. import java.io.IOException;
  15. import java.io.InputStreamReader;
  16. import java.net.Socket;
  17.  
  18. // TODO: CREATE A WRITING THREAD
  19. // here is the write thread
  20. public class WriteThread extends Thread {
  21.  
  22.     Socket socket;
  23.     BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  24.  
  25.     public WriteThread(Socket socket) throws Exception {
  26.         this.socket = socket;
  27.     }
  28.  
  29.     String message = "";// to handle the message
  30.  
  31.     @Override
  32.     public void run() {
  33.         while (true) {// start while loop for continuous conversation
  34.             try {
  35.  
  36.                 System.out.print("> ");//  for UI -- you will see when the project run :)
  37.                 message = br.readLine();// read the input
  38.  
  39.                 DataOutputStream out = new DataOutputStream(socket.getOutputStream());//to send the data
  40.                 out.writeUTF(message);// send it !
  41.                 if (message.equalsIgnoreCase("end")) {//to quit if the user want to end the conversation
  42.                     System.out.println("you have end the conversation ! ");
  43.                     break;
  44.                 }
  45.                 System.out.println(" sent ✓");// for UI
  46.             } catch (Exception ignored) {
  47.             }
  48.         }
  49.         try {// if the client end ,So we have to terminate by 3-way handshake termination
  50.             socket.close();
  51.         } catch (IOException ignored) {
  52.         }
  53.         System.err.println(" Disconnected from :" + socket.getRemoteSocketAddress());//for UI
  54.         System.exit(-1);// to be sure that the system is closed
  55.  
  56.     }
  57. }
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement