Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MyClient extends Thread{
- private DataOutputStream ostream ;
- private DataInputStream istream;
- private Socket socket;
- private boolean isPause;
- private boolean isContinue;
- private String command;
- private final String HOST;
- private final int PORT;
- private final int BUFF_SIZE=64;
- private final GuiElement guiElement;
- public MyClient(String HOST, int PORT,GuiElement guiElement) {
- this.HOST=HOST;
- this.PORT=PORT;
- this.guiElement=guiElement;
- this.isPause=true;
- this.isContinue=true;
- this.setDaemon(true);
- try {
- socket = new Socket(HOST, PORT);
- ostream = new DataOutputStream(socket.getOutputStream());
- istream = new DataInputStream(socket.getInputStream());
- } catch (Exception e) {
- isPause=false;
- isContinue=false;
- }
- start();
- }
- public void run() {
- while(isContinue) {
- //-----waiting
- synchronized(this) {
- while(isPause) {
- try {
- wait();
- } catch (InterruptedException e) {
- closeSocket();
- }
- }
- }
- //-----sending command
- sendCommand();
- }
- closeSocket();
- }
- //-----invoked from the class that creates this Client thread
- //-----when the user has clicked the enter button on the input field
- synchronized public void setCommand(String command) {
- this.command=command;
- isPause=false;
- notify();
- }
- private void sendCommand() {
- try {
- ostream.write(command.getBytes());
- ostream.flush();
- byte buf[] = new byte[BUFF_SIZE];
- int r;
- r = istream.read(buf);
- String data = new String(buf, 0, r);
- } catch (Exception e) {
- closeSocket();
- }
- Platform.runLater(() -> guiElement.print(data)); /* display a message on a GUI element */
- isPause=true;
- }
- private void closeSocket() {
- try {
- if(socket.isClosed())return;
- else socket.close();
- } catch (Exception e) {
- isPause=false;
- isContinue=false;
- }
- }
- }
Add Comment
Please, Sign In to add comment