KahnClifford

Client.java

Jul 17th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.DataInputStream;
  3. import java.io.DataOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.net.Socket;
  7.  
  8. public class Client {
  9.  
  10. Socket s = null;
  11. DataInputStream dis = null;
  12. DataOutputStream dos = null;
  13. BufferedReader br = null;
  14. String address = "localhost";
  15. int port = 3333;
  16.  
  17. public Client() {
  18. try {
  19. System.out.println("========== Establishing client connection ==========");
  20.  
  21. s = new Socket(address,port);
  22. dis = new DataInputStream(s.getInputStream());
  23. dos = new DataOutputStream(s.getOutputStream());
  24. br = new BufferedReader(new InputStreamReader(System.in));
  25.  
  26. System.out.println("========== Client connected! ==========");
  27.  
  28. String msg="",rcv="";
  29. while(!msg.equals("stop")) {
  30. msg = br.readLine();
  31. System.out.println("You: "+msg);
  32.  
  33. rcv = readSocket();
  34. System.out.println("Server: "+rcv);
  35.  
  36.  
  37. }
  38.  
  39. closeClientConnection();
  40.  
  41. } catch (Exception e) {
  42. e.printStackTrace();
  43. }
  44. }
  45.  
  46. public String writeSocket(String message) throws IOException{
  47. System.out.println("========== Write something. ==========");
  48. System.out.print("You :");
  49.  
  50. dos.writeUTF(message);
  51. dos.flush();
  52. return message;
  53. }
  54.  
  55. public String readSocket() throws IOException{
  56. System.out.println("========== Fetching message... ==========");
  57.  
  58. String recieved = dis.readUTF();
  59. return recieved;
  60. }
  61.  
  62. public void closeClientConnection() throws IOException{
  63. System.out.println("========== Closing server connection ==========");
  64. dos.close();
  65. dis.close();
  66. s.close();
  67. }
  68.  
  69. }
Add Comment
Please, Sign In to add comment