daily pastebin goal
23%
SHARE
TWEET

Untitled

a guest Jan 23rd, 2018 41 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package model;
  2.  
  3. import java.io.DataInputStream;
  4. import java.io.DataOutputStream;
  5. import java.io.IOException;
  6. import java.net.Socket;
  7.  
  8. public class ClientConnection implements Runnable {
  9.  
  10.     private Socket socket;
  11.     private DataInputStream dataInputStream;
  12.     private DataOutputStream dataOutputStream;
  13.     private boolean shouldRun = true;
  14.  
  15.     public ClientConnection(Socket socket) {
  16.         this.socket = socket;
  17.     }
  18.  
  19.     public void sendStringToServer(String string) {
  20.         try {
  21.             dataOutputStream.writeUTF(string);
  22.             dataOutputStream.flush();
  23.         } catch (IOException e) {
  24.             e.printStackTrace();
  25.             closeConnection();
  26.         }
  27.     }
  28.  
  29.     @Override
  30.     public void run() {
  31.         try {
  32.             dataInputStream = new DataInputStream(socket.getInputStream());
  33.             dataOutputStream = new DataOutputStream(socket.getOutputStream());
  34.  
  35.             while (shouldRun) {
  36.                 try {
  37.                     while (dataInputStream.available() == 0) {
  38.                         try {
  39.                             Thread.sleep(1);
  40.                         } catch (InterruptedException e) {
  41.                             e.printStackTrace();
  42.                         }
  43.                     }
  44.                     String reply = dataInputStream.readUTF();
  45.                     System.out.println(reply);
  46.                 } catch (IOException e) {
  47.                     e.printStackTrace();
  48.                     closeConnection();
  49.                 }
  50.             }
  51.         } catch (IOException e) {
  52.             e.printStackTrace();
  53.             closeConnection();
  54.         }
  55.     }
  56.  
  57.     public void closeConnection() {
  58.         try {
  59.             dataInputStream.close();
  60.             dataOutputStream.close();
  61.             socket.close();
  62.         } catch (IOException e) {
  63.             e.printStackTrace();
  64.         }
  65.     }
  66.  
  67. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top