SHARE
TWEET

Flip a coin endlessly v2 - StopSender

robertmarkbram Sep 14th, 2014 263 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package com.rmb.randomnodatabase.taskmanagement;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.io.PrintWriter;
  7. import java.net.Socket;
  8. import java.net.UnknownHostException;
  9.  
  10. /**
  11.  * Send stop signal to {@link StopListener} via port
  12.  * {@link StopListener#DEFAULT_PORT}.
  13.  *
  14.  * See: http://bit.ly/1oKSnHu
  15.  *
  16.  * @author RobertMarkBram
  17.  */
  18. public final class StopSender {
  19.  
  20.    /** Host to use. */
  21.    public static final String HOST = "localhost";
  22.  
  23.    /** Create StopSender. */
  24.    public StopSender() {
  25.    }
  26.  
  27.    /**
  28.     * Open socket and send default stop signal.
  29.     */
  30.    public void sendStopSignal() {
  31.       sendStopSignal(StopListener.STOP_SIGNAL);
  32.    }
  33.  
  34.    /**
  35.     * Open socket and send stop signal.
  36.     *
  37.     * @param message
  38.     *           whatever string you want to send to {@link StopListener}, may be
  39.     *           used for communicating error messages.
  40.     */
  41.    public void sendStopSignal(final String message) {
  42.       try (Socket socket = new Socket(HOST, StopListener.DEFAULT_PORT);
  43.             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
  44.             BufferedReader in =
  45.                   new BufferedReader(new InputStreamReader(
  46.                         socket.getInputStream()));) {
  47.          out.println(message);
  48.          final String received = in.readLine();
  49.          System.out.println(received);
  50.       } catch (UnknownHostException e) {
  51.          System.err.println("Don't know about host [" + HOST + "].");
  52.          System.exit(1);
  53.       } catch (IOException e) {
  54.          System.err.println("Couldn't get I/O for the connection to [" + HOST
  55.                + "].");
  56.          System.exit(1);
  57.       }
  58.    }
  59.  
  60.    /**
  61.     * @param args
  62.     *           - 0: stop message. May be null.
  63.     */
  64.    public static void main(final String[] args) {
  65.       StopSender sender = new StopSender();
  66.       if (args.length > 0) {
  67.          sender.sendStopSignal(args[0]);
  68.       } else {
  69.          sender.sendStopSignal();
  70.       }
  71.    }
  72.  
  73. }
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
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top