Guest User

Untitled

a guest
Jan 22nd, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. public class MyClient extends Thread{
  2.  
  3. private DataOutputStream ostream ;
  4. private DataInputStream istream;
  5. private Socket socket;
  6.  
  7. private boolean isPause;
  8. private boolean isContinue;
  9.  
  10. private String command;
  11.  
  12. private final String HOST;
  13. private final int PORT;
  14. private final int BUFF_SIZE=64;
  15. private final GuiElement guiElement;
  16.  
  17. public MyClient(String HOST, int PORT,GuiElement guiElement) {
  18. this.HOST=HOST;
  19. this.PORT=PORT;
  20. this.guiElement=guiElement;
  21. this.isPause=true;
  22. this.isContinue=true;
  23. this.setDaemon(true);
  24.  
  25. try {
  26. socket = new Socket(HOST, PORT);
  27. ostream = new DataOutputStream(socket.getOutputStream());
  28. istream = new DataInputStream(socket.getInputStream());
  29. } catch (Exception e) {
  30. isPause=false;
  31. isContinue=false;
  32. }
  33.  
  34. start();
  35. }
  36.  
  37. public void run() {
  38.  
  39. while(isContinue) {
  40.  
  41. //-----waiting
  42. synchronized(this) {
  43. while(isPause) {
  44. try {
  45. wait();
  46. } catch (InterruptedException e) {
  47. closeSocket();
  48. }
  49. }
  50. }
  51.  
  52. //-----sending command
  53. sendCommand();
  54. }
  55.  
  56. closeSocket();
  57. }
  58.  
  59. //-----invoked from the class that creates this Client thread
  60. //-----when the user has clicked the enter button on the input field
  61. synchronized public void setCommand(String command) {
  62. this.command=command;
  63. isPause=false;
  64. notify();
  65. }
  66.  
  67. private void sendCommand() {
  68.  
  69. try {
  70. ostream.write(command.getBytes());
  71. ostream.flush();
  72.  
  73. byte buf[] = new byte[BUFF_SIZE];
  74. int r;
  75.  
  76. r = istream.read(buf);
  77. String data = new String(buf, 0, r);
  78.  
  79. } catch (Exception e) {
  80. closeSocket();
  81. }
  82. Platform.runLater(() -> guiElement.print(data)); /* display a message on a GUI element */
  83. isPause=true;
  84. }
  85.  
  86. private void closeSocket() {
  87. try {
  88. if(socket.isClosed())return;
  89. else socket.close();
  90. } catch (Exception e) {
  91. isPause=false;
  92. isContinue=false;
  93. }
  94. }
  95. }
Add Comment
Please, Sign In to add comment