Example usage for java.lang Thread start

List of usage examples for java.lang Thread start

Introduction

In this page you can find the example usage for java.lang Thread start.

Prototype

public synchronized void start() 

Source Link

Document

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

Usage

From source file:ch.unizh.ini.jaer.projects.gesture.vlccontrol.TelnetClientExample.java

/***
 * Main for the TelnetClientExample./*ww w.  j av a  2  s .c  o m*/
 ***/
public static void main(String[] args) throws IOException {
    FileOutputStream fout = null;

    if (args.length < 1) {
        System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]");
        System.exit(1);
    }

    String remoteip = args[0];

    int remoteport;

    if (args.length > 1) {
        remoteport = (new Integer(args[1])).intValue();
    } else {
        remoteport = 23;
    }

    try {
        fout = new FileOutputStream("spy.log", true);
    } catch (Exception e) {
        System.err.println("Exception while opening the spy file: " + e.getMessage());
    }

    tc = new TelnetClient();

    TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
    EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
    SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);

    try {
        tc.addOptionHandler(ttopt);
        tc.addOptionHandler(echoopt);
        tc.addOptionHandler(gaopt);
    } catch (InvalidTelnetOptionException e) {
        System.err.println("Error registering option handlers: " + e.getMessage());
    }

    while (true) {
        boolean end_loop = false;
        try {
            tc.connect(remoteip, remoteport);

            Thread reader = new Thread(new TelnetClientExample());
            tc.registerNotifHandler(new TelnetClientExample());
            System.out.println("TelnetClientExample");
            System.out.println("Type AYT to send an AYT telnet command");
            System.out.println("Type OPT to print a report of status of options (0-24)");
            System.out.println("Type REGISTER to register a new SimpleOptionHandler");
            System.out.println("Type UNREGISTER to unregister an OptionHandler");
            System.out.println("Type SPY to register the spy (connect to port 3333 to spy)");
            System.out.println("Type UNSPY to stop spying the connection");

            reader.start();
            OutputStream outstr = tc.getOutputStream();

            byte[] buff = new byte[1024];
            int ret_read = 0;

            do {
                try {
                    ret_read = System.in.read(buff);
                    if (ret_read > 0) {
                        if ((new String(buff, 0, ret_read)).startsWith("AYT")) {
                            try {
                                System.out.println("Sending AYT");

                                System.out.println("AYT response:" + tc.sendAYT(5000));
                            } catch (Exception e) {
                                System.err.println("Exception waiting AYT response: " + e.getMessage());
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("OPT")) {
                            System.out.println("Status of options:");
                            for (int ii = 0; ii < 25; ii++) {
                                System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii)
                                        + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii));
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("REGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = (new Integer(st.nextToken())).intValue();
                                boolean initlocal = (new Boolean(st.nextToken())).booleanValue();
                                boolean initremote = (new Boolean(st.nextToken())).booleanValue();
                                boolean acceptlocal = (new Boolean(st.nextToken())).booleanValue();
                                boolean acceptremote = (new Boolean(st.nextToken())).booleanValue();
                                SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal,
                                        initremote, acceptlocal, acceptremote);
                                tc.addOptionHandler(opthand);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error registering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid REGISTER command.");
                                    System.err.println(
                                            "Use REGISTER optcode initlocal initremote acceptlocal acceptremote");
                                    System.err.println("(optcode is an integer.)");
                                    System.err.println(
                                            "(initlocal, initremote, acceptlocal, acceptremote are boolean)");
                                }
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("UNREGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = (new Integer(st.nextToken())).intValue();
                                tc.deleteOptionHandler(opcode);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error unregistering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid UNREGISTER command.");
                                    System.err.println("Use UNREGISTER optcode");
                                    System.err.println("(optcode is an integer)");
                                }
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("SPY")) {
                            try {
                                tc.registerSpyStream(fout);
                            } catch (Exception e) {
                                System.err.println("Error registering the spy");
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("UNSPY")) {
                            tc.stopSpyStream();
                        } else {
                            try {
                                outstr.write(buff, 0, ret_read);
                                outstr.flush();
                            } catch (Exception e) {
                                end_loop = true;
                            }
                        }
                    }
                } catch (Exception e) {
                    System.err.println("Exception while reading keyboard:" + e.getMessage());
                    end_loop = true;
                }
            } while ((ret_read > 0) && (end_loop == false));

            try {
                tc.disconnect();
            } catch (Exception e) {
                System.err.println("Exception while connecting:" + e.getMessage());
            }
        } catch (Exception e) {
            System.err.println("Exception while connecting:" + e.getMessage());
            System.exit(1);
        }
    }
}

From source file:com.hzih.sslvpn.servlet.TelnetClientExample.java

/**
 * Main for the TelnetClientExample.//w w w. j  av a2 s . c o  m
 * *
 */
public static void main(String[] args) throws Exception {
    FileOutputStream fout = null;

    if (args.length < 1) {
        System.err.println("Usage: TelnetClientExample1 <remote-ip> [<remote-port>]");
        System.exit(1);
    }

    String remoteip = args[0];

    int remoteport;

    if (args.length > 1) {
        remoteport = (new Integer(args[1])).intValue();
    } else {
        remoteport = 23;
    }

    try {
        fout = new FileOutputStream("spy.log", true);
    } catch (IOException e) {
        System.err.println("Exception while opening the spy file: " + e.getMessage());
    }

    tc = new TelnetClient();

    TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
    EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
    SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);

    try {
        tc.addOptionHandler(ttopt);
        tc.addOptionHandler(echoopt);
        tc.addOptionHandler(gaopt);
    } catch (InvalidTelnetOptionException e) {
        System.err.println("Error registering option handlers: " + e.getMessage());
    }

    while (true) {
        boolean end_loop = false;
        try {
            tc.connect(remoteip, remoteport);

            Thread reader = new Thread(new TelnetClientExample());
            tc.registerNotifHandler(new TelnetClientExample());
            System.out.println("TelnetClientExample");
            System.out.println("Type AYT to send an AYT telnet command");
            System.out.println("Type OPT to print a report of status of options (0-24)");
            System.out.println("Type REGISTER to register a new SimpleOptionHandler");
            System.out.println("Type UNREGISTER to unregister an OptionHandler");
            System.out.println("Type SPY to register the spy (connect to port 3333 to spy)");
            System.out.println("Type UNSPY to stop spying the connection");

            reader.start();
            OutputStream outstr = tc.getOutputStream();

            byte[] buff = new byte[1024];
            int ret_read = 0;

            do {
                try {
                    ret_read = System.in.read(buff);
                    if (ret_read > 0) {
                        if ((new String(buff, 0, ret_read)).startsWith("AYT")) {
                            try {
                                System.out.println("Sending AYT");

                                System.out.println("AYT response:" + tc.sendAYT(5000));
                            } catch (IOException e) {
                                System.err.println("Exception waiting AYT response: " + e.getMessage());
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("OPT")) {
                            System.out.println("Status of options:");
                            for (int ii = 0; ii < 25; ii++) {
                                System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii)
                                        + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii));
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("REGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = Integer.parseInt(st.nextToken());
                                boolean initlocal = Boolean.parseBoolean(st.nextToken());
                                boolean initremote = Boolean.parseBoolean(st.nextToken());
                                boolean acceptlocal = Boolean.parseBoolean(st.nextToken());
                                boolean acceptremote = Boolean.parseBoolean(st.nextToken());
                                SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal,
                                        initremote, acceptlocal, acceptremote);
                                tc.addOptionHandler(opthand);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error registering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid REGISTER command.");
                                    System.err.println(
                                            "Use REGISTER optcode initlocal initremote acceptlocal acceptremote");
                                    System.err.println("(optcode is an integer.)");
                                    System.err.println(
                                            "(initlocal, initremote, acceptlocal, acceptremote are boolean)");
                                }
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("UNREGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = (new Integer(st.nextToken())).intValue();
                                tc.deleteOptionHandler(opcode);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error unregistering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid UNREGISTER command.");
                                    System.err.println("Use UNREGISTER optcode");
                                    System.err.println("(optcode is an integer)");
                                }
                            }
                        } else if ((new String(buff, 0, ret_read)).startsWith("SPY")) {
                            tc.registerSpyStream(fout);
                        } else if ((new String(buff, 0, ret_read)).startsWith("UNSPY")) {
                            tc.stopSpyStream();
                        } else {
                            try {
                                outstr.write(buff, 0, ret_read);
                                outstr.flush();
                            } catch (IOException e) {
                                end_loop = true;
                            }
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Exception while reading keyboard:" + e.getMessage());
                    end_loop = true;
                }
            } while ((ret_read > 0) && (end_loop == false));

            try {
                tc.disconnect();
            } catch (IOException e) {
                System.err.println("Exception while connecting:" + e.getMessage());
            }
        } catch (IOException e) {
            System.err.println("Exception while connecting:" + e.getMessage());
            System.exit(1);
        }
    }
}

From source file:org.argouml.application.Main.java

/**
 * The main entry point of ArgoUML./*from  w  w  w. j  a va 2s. co  m*/
 * @param args command line parameters
 */
public static void main(String[] args) {
    try {
        LOG.info("ArgoUML Started.");

        SimpleTimer st = new SimpleTimer();
        st.mark("begin");

        initPreinitialize();

        st.mark("arguments");
        parseCommandLine(args);

        // Register our last chance exception handler
        AwtExceptionHandler.registerExceptionHandler();

        // Get the splash screen up as early as possible
        st.mark("create splash");
        SplashScreen splash = null;
        if (!batch) {
            // We have to do this to set the LAF for the splash screen
            st.mark("initialize laf");
            LookAndFeelMgr.getInstance().initializeLookAndFeel();
            if (theTheme != null) {
                LookAndFeelMgr.getInstance().setCurrentTheme(theTheme);
            }
            if (doSplash) {
                splash = initializeSplash();
            }
        }

        // main initialization happens here
        ProjectBrowser pb = initializeSubsystems(st, splash);

        // Needs to happen after initialization is done & modules loaded
        st.mark("perform commands");
        if (batch) {
            // TODO: Add an "open most recent project" command so that 
            // command state can be decoupled from user settings?
            performCommandsInternal(commands);
            commands = null;

            System.out.println("Exiting because we are running in batch.");
            new ActionExit().doCommand(null);
            return;
        }

        if (reloadRecent && projectName == null) {
            projectName = getMostRecentProject();
        }

        URL urlToOpen = null;
        if (projectName != null) {
            projectName = PersistenceManager.getInstance().fixExtension(projectName);
            urlToOpen = projectUrl(projectName, urlToOpen);
        }

        openProject(st, splash, pb, urlToOpen);

        st.mark("perspectives");
        if (splash != null) {
            splash.updateProgress(75);
        }

        st.mark("open window");
        updateProgress(splash, 95, "statusmsg.bar.open-project-browser");
        ArgoFrame.getFrame().setVisible(true);

        st.mark("close splash");
        if (splash != null) {
            splash.setVisible(false);
            splash.dispose();
            splash = null;
        }

        // Aufrufen der Aufgabenstellung
        if (taskID != null) {
            ActionShowTask task = new ActionShowTask();
            task.showTask();
            if (projectName == null && ActionShowTask.taskDescription != null
                    && (ActionShowTask.taskDescription.toLowerCase().contains("aktivittsdiagramm")
                            || ActionShowTask.taskDescription.toLowerCase().contains("aktivitts-diagramm")
                            || ActionShowTask.taskDescription.toLowerCase().contains("aktivit&auml;tsdiagramm")
                            || ActionShowTask.taskDescription.toLowerCase().contains("aktivit&auml;ts-diagramm")
                            || ActionShowTask.taskDescription.toLowerCase().contains("activity diagram")
                            || ActionShowTask.taskDescription.toLowerCase().contains("activity-diagram"))) {
                new ActionActivityDiagram().actionPerformed(null);
            }
        }

        performCommands(commands);
        commands = null;

        st.mark("start critics");
        Runnable startCritics = new StartCritics();
        Main.addPostLoadAction(startCritics);

        st.mark("start loading modules");
        Runnable moduleLoader = new LoadModules();
        Main.addPostLoadAction(moduleLoader);

        PostLoad pl = new PostLoad(postLoadActions);
        Thread postLoadThead = new Thread(pl);
        postLoadThead.start();

        LOG.info("");
        LOG.info("profile of load time ############");
        for (Enumeration i = st.result(); i.hasMoreElements();) {
            LOG.info(i.nextElement());
        }
        LOG.info("#################################");
        LOG.info("");

        st = null;
        ArgoFrame.getFrame().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));

        // Andreas: just temporary: a warning dialog for uml2...
        if (showUml2warning && Model.getFacade().getUmlVersion().startsWith("2")) {
            JOptionPane.showMessageDialog(ArgoFrame.getFrame(),
                    "You are running an experimental version not meant for productive work!",
                    "UML2 pre-alpha warning", JOptionPane.WARNING_MESSAGE);
        }

        //ToolTipManager.sharedInstance().setInitialDelay(500);
        ToolTipManager.sharedInstance().setDismissDelay(50000000);
    } catch (Throwable t) {
        try {
            LOG.fatal("Fatal error on startup.  ArgoUML failed to start", t);
        } finally {
            System.out.println("Fatal error on startup.  " + "ArgoUML failed to start.");
            t.printStackTrace();
            System.exit(1);
        }
    }
}

From source file:clientpaxos.ClientPaxos.java

/**
 * @param args the command line arguments
 *///from  ww  w.  j  a  v a2  s .c o  m
public static void main(String[] args) throws IOException, InterruptedException, Exception {
    // TODO code application logic here

    String host = "";
    int port = 0;

    try (BufferedReader br = new BufferedReader(new FileReader("ipserver.txt"))) {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        if (line != null) {
            host = line;
            line = br.readLine();
            if (line != null) {
                port = Integer.parseInt(line);
            }
        }
    }

    scanner = new Scanner(System.in);

    //System.out.print("Input server IP hostname : ");
    //host = scan.nextLine();
    //System.out.print("Input server Port : ");
    //port = scan.nextInt();
    //scan.nextLine();
    tcpSocket = new Socket(host, port);
    System.out.println("Connected");
    Thread t = new Thread(new StringGetter());
    t.start();
    while (true) {
        sleep(100);
        if (!voteInput) {
            System.out.print("COMMAND : ");
        }
        //send msg to server
        String msg = scanner.next();
        //if ((day && isAlive == 1) || (!day && role.equals("werewolf") && isAlive == 1)) {
        ParseCommand(msg);
        //}
    }
}

From source file:org.eclipse.swt.snippets.Snippet130.java

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("Snippet 130");
    shell.setLayout(new GridLayout());
    final Text text = new Text(shell, SWT.MULTI | SWT.BORDER | SWT.V_SCROLL);
    text.setLayoutData(new GridData(GridData.FILL_BOTH));
    final int[] nextId = new int[1];
    Button b = new Button(shell, SWT.PUSH);
    b.setText("invoke long running job");
    b.addSelectionListener(widgetSelectedAdapter(e -> {
        Runnable longJob = new Runnable() {
            boolean done = false;
            int id;

            @Override//w  ww.j a v  a2s  .  co  m
            public void run() {
                Thread thread = new Thread(() -> {
                    id = nextId[0]++;
                    display.syncExec(() -> {
                        if (text.isDisposed())
                            return;
                        text.append("\nStart long running task " + id);
                    });
                    for (int i = 0; i < 100000; i++) {
                        if (display.isDisposed())
                            return;
                        System.out.println("do task that takes a long time in a separate thread " + id);
                    }
                    if (display.isDisposed())
                        return;
                    display.syncExec(() -> {
                        if (text.isDisposed())
                            return;
                        text.append("\nCompleted long running task " + id);
                    });
                    done = true;
                    display.wake();
                });
                thread.start();
                while (!done && !shell.isDisposed()) {
                    if (!display.readAndDispatch())
                        display.sleep();
                }
            }
        };
        BusyIndicator.showWhile(display, longJob);
    }));
    shell.setSize(250, 150);
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:GenericClient.java

public static void main(String[] args) throws IOException {
    try {/*from  w  w w.  ja va2  s.  com*/
        // Check the number of arguments
        if (args.length != 2)
            throw new IllegalArgumentException("Wrong number of args");

        // Parse the host and port specifications
        String host = args[0];
        int port = Integer.parseInt(args[1]);

        // Connect to the specified host and port
        Socket s = new Socket(host, port);

        // Set up streams for reading from and writing to the server.
        // The from_server stream is final for use in the inner class below
        final Reader from_server = new InputStreamReader(s.getInputStream());
        PrintWriter to_server = new PrintWriter(s.getOutputStream());

        // Set up streams for reading from and writing to the console
        // The to_user stream is final for use in the anonymous class below
        BufferedReader from_user = new BufferedReader(new InputStreamReader(System.in));
        // Pass true for auto-flush on println()
        final PrintWriter to_user = new PrintWriter(System.out, true);

        // Tell the user that we've connected
        to_user.println("Connected to " + s.getInetAddress() + ":" + s.getPort());

        // Create a thread that gets output from the server and displays
        // it to the user. We use a separate thread for this so that we
        // can receive asynchronous output
        Thread t = new Thread() {
            public void run() {
                char[] buffer = new char[1024];
                int chars_read;
                try {
                    // Read characters from the server until the
                    // stream closes, and write them to the console
                    while ((chars_read = from_server.read(buffer)) != -1) {
                        to_user.write(buffer, 0, chars_read);
                        to_user.flush();
                    }
                } catch (IOException e) {
                    to_user.println(e);
                }

                // When the server closes the connection, the loop above
                // will end. Tell the user what happened, and call
                // System.exit(), causing the main thread to exit along
                // with this one.
                to_user.println("Connection closed by server.");
                System.exit(0);
            }
        };

        // Now start the server-to-user thread
        t.start();

        // In parallel, read the user's input and pass it on to the server.
        String line;
        while ((line = from_user.readLine()) != null) {
            to_server.print(line + "\r\n");
            to_server.flush();
        }

        // If the user types a Ctrl-D (Unix) or Ctrl-Z (Windows) to end
        // their input, we'll get an EOF, and the loop above will exit.
        // When this happens, we stop the server-to-user thread and close
        // the socket.

        s.close();
        to_user.println("Connection closed by client.");
        System.exit(0);
    }
    // If anything goes wrong, print an error message
    catch (Exception e) {
        System.err.println(e);
        System.err.println("Usage: java GenericClient <hostname> <port>");
    }
}

From source file:AnotherDeadLock.java

public static void main(String[] args) {
    final Object resource1 = "resource1";
    final Object resource2 = "resource2";
    // t1 tries to lock resource1 then resource2
    Thread t1 = new Thread() {
        public void run() {
            // Lock resource 1
            synchronized (resource1) {
                System.out.println("Thread 1: locked resource 1");

                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                }/*from ww w .j  a va  2s.  c  o m*/

                synchronized (resource2) {
                    System.out.println("Thread 1: locked resource 2");
                }
            }
        }
    };

    // t2 tries to lock resource2 then resource1
    Thread t2 = new Thread() {
        public void run() {
            synchronized (resource2) {
                System.out.println("Thread 2: locked resource 2");

                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                }

                synchronized (resource1) {
                    System.out.println("Thread 2: locked resource 1");
                }
            }
        }
    };

    // If all goes as planned, deadlock will occur,
    // and the program will never exit.
    t1.start();
    t2.start();
}

From source file:net.sf.jhylafax.JHylaFAX.java

/**
 * @param args//from w w  w .  j av  a2  s. com
 */
public static void main(final String[] args) {
    final ArgsHandler handler = new ArgsHandler();
    handler.evaluate(args);

    evaluateArgumentsPreVisible(handler);

    ThreadGroup tg = new ThreadGroup("JHylaFAXThreadGroup") {
        public void uncaughtException(Thread t, Throwable e) {
            e.printStackTrace();
        }
    };

    //      System.setProperty("sun.awt.exception.handler", 
    //                     "xnap.util.XNapAWTExceptionHandler");
    Thread mainRunner = new Thread(tg, "JHylaFAXMain") {
        public void run() {
            setContextClassLoader(JHylaFAX.class.getClassLoader());

            JHylaFAX app = new JHylaFAX();
            app.setVisible(true);

            app.evaluateArgumentsPostVisible(handler);
        }
    };
    mainRunner.start();
}

From source file:org.eclipse.swt.snippets.Snippet151.java

public static void main(String[] args) {
    final Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 151");
    shell.setLayout(new FillLayout());
    final Table table = new Table(shell, SWT.BORDER | SWT.VIRTUAL);
    table.addListener(SWT.SetData, e -> {
        TableItem item = (TableItem) e.item;
        int index = table.indexOf(item);
        item.setText("Item " + data[index]);
    });/* ww  w. ja  v  a  2  s  .  co  m*/
    Thread thread = new Thread() {
        @Override
        public void run() {
            int count = 0;
            Random random = new Random();
            while (count++ < 500) {
                if (table.isDisposed())
                    return;
                // add 10 random numbers to array and sort
                int grow = 10;
                int[] newData = new int[data.length + grow];
                System.arraycopy(data, 0, newData, 0, data.length);
                int index = data.length;
                data = newData;
                for (int j = 0; j < grow; j++) {
                    data[index++] = random.nextInt();
                }
                Arrays.sort(data);
                display.syncExec(() -> {
                    if (table.isDisposed())
                        return;
                    table.setItemCount(data.length);
                    table.clearAll();
                });
                try {
                    Thread.sleep(500);
                } catch (Throwable t) {
                }
            }
        }
    };
    thread.start();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:correospingtelnet.Telnet.java

public static void main(String[] args) throws Exception {
    FileOutputStream fout = null;

    String remoteip = "64.62.142.154";

    int remoteport = 23;

    try {//  w  w  w. ja va 2  s . c  om
        fout = new FileOutputStream("spy.log", true);
    } catch (IOException e) {
        System.err.println("Exception while opening the spy file: " + e.getMessage());
    }

    tc = new TelnetClient();

    TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
    EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
    SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);

    try {
        tc.addOptionHandler(ttopt);
        tc.addOptionHandler(echoopt);
        tc.addOptionHandler(gaopt);
    } catch (InvalidTelnetOptionException e) {
        System.err.println("Error registering option handlers: " + e.getMessage());
    }

    while (true) {
        boolean end_loop = false;
        try {
            tc.connect(remoteip, remoteport);

            Thread reader = new Thread(new Telnet());
            tc.registerNotifHandler(new Telnet());
            System.out.println("TelnetClientExample");
            System.out.println("Type AYT to send an AYT telnet command");
            System.out.println("Type OPT to print a report of status of options (0-24)");
            System.out.println("Type REGISTER to register a new SimpleOptionHandler");
            System.out.println("Type UNREGISTER to unregister an OptionHandler");
            System.out.println("Type SPY to register the spy (connect to port 3333 to spy)");
            System.out.println("Type UNSPY to stop spying the connection");
            System.out.println("Type ^[A-Z] to send the control character; use ^^ to send ^");

            reader.start();
            OutputStream outstr = tc.getOutputStream();

            byte[] buff = new byte[1024];
            int ret_read = 0;

            do {
                try {
                    ret_read = System.in.read(buff);
                    if (ret_read > 0) {
                        final String line = new String(buff, 0, ret_read); // deliberate use of default charset
                        if (line.startsWith("AYT")) {
                            try {
                                System.out.println("Sending AYT");

                                System.out.println("AYT response:" + tc.sendAYT(5000));
                            } catch (IOException e) {
                                System.err.println("Exception waiting AYT response: " + e.getMessage());
                            }
                        } else if (line.startsWith("OPT")) {
                            System.out.println("Status of options:");
                            for (int ii = 0; ii < 25; ii++) {
                                System.out.println("Local Option " + ii + ":" + tc.getLocalOptionState(ii)
                                        + " Remote Option " + ii + ":" + tc.getRemoteOptionState(ii));
                            }
                        } else if (line.startsWith("REGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = Integer.parseInt(st.nextToken());
                                boolean initlocal = Boolean.parseBoolean(st.nextToken());
                                boolean initremote = Boolean.parseBoolean(st.nextToken());
                                boolean acceptlocal = Boolean.parseBoolean(st.nextToken());
                                boolean acceptremote = Boolean.parseBoolean(st.nextToken());
                                SimpleOptionHandler opthand = new SimpleOptionHandler(opcode, initlocal,
                                        initremote, acceptlocal, acceptremote);
                                tc.addOptionHandler(opthand);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error registering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid REGISTER command.");
                                    System.err.println(
                                            "Use REGISTER optcode initlocal initremote acceptlocal acceptremote");
                                    System.err.println("(optcode is an integer.)");
                                    System.err.println(
                                            "(initlocal, initremote, acceptlocal, acceptremote are boolean)");
                                }
                            }
                        } else if (line.startsWith("UNREGISTER")) {
                            StringTokenizer st = new StringTokenizer(new String(buff));
                            try {
                                st.nextToken();
                                int opcode = (new Integer(st.nextToken())).intValue();
                                tc.deleteOptionHandler(opcode);
                            } catch (Exception e) {
                                if (e instanceof InvalidTelnetOptionException) {
                                    System.err.println("Error unregistering option: " + e.getMessage());
                                } else {
                                    System.err.println("Invalid UNREGISTER command.");
                                    System.err.println("Use UNREGISTER optcode");
                                    System.err.println("(optcode is an integer)");
                                }
                            }
                        } else if (line.startsWith("SPY")) {
                            tc.registerSpyStream(fout);
                        } else if (line.startsWith("UNSPY")) {
                            tc.stopSpyStream();
                        } else if (line.matches("^\\^[A-Z^]\\r?\\n?$")) {
                            byte toSend = buff[1];
                            if (toSend == '^') {
                                outstr.write(toSend);
                            } else {
                                outstr.write(toSend - 'A' + 1);
                            }
                            outstr.flush();
                        } else {
                            try {
                                outstr.write(buff, 0, ret_read);
                                outstr.flush();
                            } catch (IOException e) {
                                end_loop = true;
                            }
                        }
                    }
                } catch (IOException e) {
                    System.err.println("Exception while reading keyboard:" + e.getMessage());
                    end_loop = true;
                }
            } while ((ret_read > 0) && (end_loop == false));

            try {
                tc.disconnect();
            } catch (IOException e) {
                System.err.println("Exception while connecting:" + e.getMessage());
            }
        } catch (IOException e) {
            System.err.println("Exception while connecting:" + e.getMessage());
            System.exit(1);
        }
    }
}