Example usage for java.net ServerSocket close

List of usage examples for java.net ServerSocket close

Introduction

In this page you can find the example usage for java.net ServerSocket close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this socket.

Usage

From source file:Main.java

public static void main(String args[]) throws Exception {
    ServerSocket ssock = new ServerSocket(1234);
    Socket sock = ssock.accept();
    ssock.close();

    PrintStream pstream = new PrintStream(sock.getOutputStream());
    for (int i = 100; i >= 0; i--) {
        pstream.println(i);//ww w.j  a  v  a  2  s  .c om
    }
    pstream.close();
    sock.close();
}

From source file:Main.java

public static void main(String args[]) throws Exception {
    ServerSocket ssock = new ServerSocket(1234);
    Socket sock = ssock.accept();
    ssock.close();

    PrintStream pstream = new PrintStream(sock.getOutputStream());
    pstream.print("count? ");
    BufferedReader input = new BufferedReader(new InputStreamReader(sock.getInputStream()));
    String line = input.readLine();
    pstream.println("");
    int count = Integer.parseInt(line);
    for (int i = count; i >= 0; i--) {
        pstream.println(i);/*from  w ww.  j  a v a2s  .  c  om*/
    }
    pstream.close();
    sock.close();
}

From source file:AnotherBeerServer.java

public static void main(String args[]) throws Exception {
    ServerSocket ssock = new ServerSocket(1234);
    System.out.println("Listening");
    Socket sock = ssock.accept();
    ssock.close(); // no more connects

    PrintStream ps = new PrintStream(sock.getOutputStream());

    // ask for count
    ps.print("count? ");
    BufferedReader input = new BufferedReader(new InputStreamReader(sock.getInputStream()));

    // read and parse it
    String line = input.readLine();
    ps.println("");
    int count = Integer.parseInt(line);
    for (int i = count; i >= 0; i--) {
        ps.println(i + " Java Source and Support.");
    }//ww  w.  j  ava  2  s.  c  om
    ps.close();
    sock.close();
}

From source file:org.apache.hadoop.gateway.security.ldap.SimpleLdapDirectoryServer.java

public static void main(String[] args) throws Exception {
    PropertyConfigurator.configure(System.getProperty("log4j.configuration"));

    SimpleLdapDirectoryServer ldap;// w  ww . j  av  a 2  s .  c o  m

    File file;
    if (args.length < 1) {
        file = new File("conf/users.ldif");
    } else {
        File dir = new File(args[0]);
        if (!dir.exists() || !dir.isDirectory()) {
            throw new FileNotFoundException(dir.getAbsolutePath());
        }
        file = new File(dir, "users.ldif");
    }

    if (!file.exists() || !file.canRead()) {
        throw new FileNotFoundException(file.getAbsolutePath());
    }

    int port = 33389;

    // Make sure the port is free.
    ServerSocket socket = new ServerSocket(port);
    socket.close();

    TcpTransport transport = new TcpTransport(port);
    ldap = new SimpleLdapDirectoryServer("dc=hadoop,dc=apache,dc=org", file, transport);
    ldap.start();
}

From source file:org.kchine.r.server.CoreMain.java

public static void main(String[] args) throws Exception {
    PoolUtils.initLog4J();//www  . java  2s  .c  o m

    if (System.getProperty("rmi.port.start") != null && !System.getProperty("rmi.port.start").equals("")) {

        int width = 300;
        if (System.getProperty("submit.ssh.rmi.port.width") != null
                && !System.getProperty("submit.ssh.rmi.port.width").equals("")) {
            width = Integer.decode(System.getProperty("submit.ssh.rmi.port.width"));
        }

        int rmi_port_start = Integer.decode(System.getProperty("rmi.port.start"));
        Integer valid_port = null;
        for (int i = 0; i < (width / RServantImpl.PORT_RANGE_WIDTH); ++i) {
            try {
                ServerSocket s = new ServerSocket(rmi_port_start + i * RServantImpl.PORT_RANGE_WIDTH);
                s.close();
                valid_port = rmi_port_start + i * RServantImpl.PORT_RANGE_WIDTH;
                break;
            } catch (Exception e) {
            }
        }
        if (valid_port == null) {
            log.info("all available ports are taken, can't create server");
            System.exit(0);
        }

        System.setProperty("rmi.port.start", "" + valid_port);
        log.info("rmi.port.start:" + System.getProperty("rmi.port.start"));
    }

    Vector<URL> codeUrls = new Vector<URL>();
    if (args.length > 0) {
        for (int i = 0; i < args.length; ++i) {
            codeUrls.add(new URL(args[i]));
        }
    } else {
        /*
        String jar = CoreMain.class.getResource("/org/kchine/r/server/CoreMain.class").toString();
        if (jar.startsWith("jar:")) {
           String jarfile = jar.substring("jar:".length(), jar.length() - "/org/kchine/r/server/CoreMain.class".length() - 1);
           System.out.println("jarfile:" + jarfile);
           try {
              codeUrls.add(new URL(jarfile));
           } catch (Exception e) {
              e.printStackTrace();
           }
        }
        */
    }

    boolean wait = System.getProperty("wait") == null || System.getProperty("wait").equals("")
            || new Boolean(System.getProperty("wait"));

    RServices r = null;

    if (ServerDefaults.isRegistryAccessible()) {
        String name = System.getProperty("name");
        String rbinary = System.getProperty("r.binary");
        r = ServerManager.createR(rbinary, false, wait ? false : true, PoolUtils.getHostIp(),
                LocalHttpServer.getLocalHttpServerPort(), ServerManager.getNamingInfo(),
                ServerDefaults._memoryMin, ServerDefaults._memoryMax, name, false,
                (URL[]) codeUrls.toArray(new URL[0]), System.getProperty("log.file"), "standard",
                new Runnable() {
                    public void run() {
                        System.exit(0);
                    }
                }, null);

    } else {
        System.out.println("Can't Launch R Server, Rmi Registry is not accessible!!");
    }

    /*
     * inet httpServerPort=-1; try { if
     * (System.getProperty("http.port")!=null &&
     * !System.getProperty("http.port").equals("")) {
     * httpServerPort=Integer.decode(System.getProperty("http.port")); } }
     * catch (Exception e) {} if (httpServerPort!=-1) {
     * r.startHttpServer(httpServerPort); }
     */

    if (wait) {
        while (true) {
            try {
                Thread.sleep(100);
            } catch (Exception e) {
            }
        }
    } else {
        System.exit(0);
    }
}

From source file:EchoClient.java

 public static void main(String[] args) throws IOException {
   ServerSocket serverSocket = null;
   boolean listening = true;

   try {//from ww  w .  ja va2 s  .c  o m
      serverSocket = new ServerSocket(4444);
   } catch (IOException e) {
      System.err.println("Could not listen on port: 4444.");
      System.exit(-1);
   }

   while (listening)
      new KKMultiServerThread(serverSocket.accept()).start();

   serverSocket.close();
}

From source file:EchoClient.java

 public static void main(String[] args) throws IOException {

   ServerSocket serverSocket = null;
   try {/*  w  w  w  .  j  a va2s  .  c  o  m*/
      serverSocket = new ServerSocket(4444);
   } catch (IOException e) {
      System.err.println("Could not listen on port: 4444.");
      System.exit(1);
   }

   Socket clientSocket = null;
   try {
      clientSocket = serverSocket.accept();
   } catch (IOException e) {
      System.err.println("Accept failed.");
      System.exit(1);
   }

   PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
   BufferedReader in = new BufferedReader(new InputStreamReader(
         clientSocket.getInputStream()));
   String inputLine, outputLine;
   KnockKnockProtocol kkp = new KnockKnockProtocol();

   outputLine = kkp.processInput(null);
   out.println(outputLine);

   while ((inputLine = in.readLine()) != null) {
      outputLine = kkp.processInput(inputLine);
      out.println(outputLine);
      if (outputLine.equals("Bye."))
         break;
   }
   out.close();
   in.close();
   clientSocket.close();
   serverSocket.close();
}

From source file:Logi.GSeries.Service.LogiGSKService.java

/**
 * @param args the command line arguments
 */// ww w.  jav a  2s. co m
public static void main(String[] args) {
    SystemTray.DEBUG = false;

    Settings settings;
    if (IOOperations.currentSettingsExist()) {
        settings = IOOperations.loadCurrentSettingsObjectFromFile();
    } else {
        settings = new Settings();
    }

    LogiGSKService l = new LogiGSKService();
    if (settings.getShowSystemTray()) {
        l.showSystemTray();
    } else {
        l.hideSystemTray();
    }
    l.begin();
    try {
        String dataFolderPath = IOOperations.getLocalDataDirectoryPath();
        File dataFolder = new File(dataFolderPath);
        if (!dataFolder.exists()) {
            dataFolder.mkdir();
        }
        String logFolderPath = IOOperations.getLogDirectoryPath();
        File logFolder = new File(logFolderPath);
        if (!logFolder.exists()) {
            logFolder.mkdir();
        }
        FileHandler fileHandler = new FileHandler(logFolderPath + "LogiGSK.log", FILE_SIZE, 3);
        fileHandler.setLevel(Level.ALL);
        logger.setLevel(Level.ALL);
        logger.addHandler(fileHandler);
    } catch (IOException | SecurityException ex) {
        Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex);
    }
    int clientNumber = 0;
    ServerSocket listener = null;
    PropertyConfigurator.configure(LogiGSKService.class.getResource("/Logi/GSeries/Service/log4j.properties"));
    reloading = true;
    boolean firstTime = true;
    while (reloading) {
        listener = null;
        if (reloading && !firstTime) {
            if (IOOperations.currentSettingsExist()) {
                settings = IOOperations.loadCurrentSettingsObjectFromFile();
            } else {
                settings = new Settings();
            }
        }
        firstTime = false;
        reloading = false;
        running = true;
        try {
            listener = new ServerSocket(settings.getPort(), 0, InetAddress.getByName(null));
            while (running) {
                new Manager(listener.accept(), clientNumber++, logger).start();
            }
        } catch (IOException ex) {
            Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (listener != null) {
                try {
                    listener.close();
                } catch (IOException ex) {
                    Logger.getLogger(LogiGSKService.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}

From source file:com.annuletconsulting.homecommand.server.HomeCommand.java

/**
 * This class will accept commands from a node in each room. For it to react to events on the server
 * computer, it must be also running as a node.  However the server can cause all nodes to react
 * to an event happening on any node, such as an email or text arriving.  A call on a node device
 * could pause all music devices, for example.
 * //w w  w .ja v  a  2s  .  c o m
 * @param args
 */
public static void main(String[] args) {
    try {
        socket = Integer.parseInt(HomeComandProperties.getInstance().getServerPort());
        nonJavaUserModulesPath = HomeComandProperties.getInstance().getNonJavaUserDir();
    } catch (Exception exception) {
        System.out.println("Error loading from properties file.");
        exception.printStackTrace();
    }
    try {
        sharedKey = HomeComandProperties.getInstance().getSharedKey();
        if (sharedKey == null)
            System.out.println("shared_key is null, commands without valid signatures will be processed.");
    } catch (Exception exception) {
        System.out.println("shared_key not found in properties file.");
        exception.printStackTrace();
    }
    try {
        if (args.length > 0) {
            String arg0 = args[0];
            if (arg0.equals("help") || arg0.equals("?") || arg0.equals("usage") || arg0.equals("-help")
                    || arg0.equals("-?")) {
                System.out.println(
                        "The defaults can be changed by editing the HomeCommand.properties file, or you can override them temporarily using command line options.");
                System.out.println("\nHome Command Server command line overrride usage:");
                System.out.println(
                        "hcserver [server_port] [java_user_module_directory] [non_java_user_module_directory]"); //TODO make hcserver.sh
                System.out.println("\nDefaults:");
                System.out.println("server_port: " + socket);
                System.out.println("java_user_module_directory: " + userModulesPath);
                System.out.println("non_java_user_module_directory: " + nonJavaUserModulesPath);
                System.out.println("\n2013 | Annulet, LLC");
            }
            socket = Integer.parseInt(arg0);
        }
        if (args.length > 1)
            userModulesPath = args[1];
        if (args.length > 2)
            nonJavaUserModulesPath = args[2];

        System.out.println("Config loaded, initializing modules.");
        modules.add(new HueLightModule());
        System.out.println("HueLightModule initialized.");
        modules.add(new QuestionModule());
        System.out.println("QuestionModule initialized.");
        modules.add(new MathModule());
        System.out.println("MathModule initialized.");
        modules.add(new MusicModule());
        System.out.println("MusicModule initialized.");
        modules.add(new NonCopyrightInfringingGenericSpaceExplorationTVShowModule());
        System.out.println("NonCopyrightInfringingGenericSpaceExplorationTVShowModule initialized.");
        modules.add(new HelpModule());
        System.out.println("HelpModule initialized.");
        modules.add(new SetUpModule());
        System.out.println("SetUpModule initialized.");
        modules.addAll(NonJavaUserModuleLoader.loadModulesAt(nonJavaUserModulesPath));
        System.out.println("NonJavaUserModuleLoader initialized.");
        ServerSocket serverSocket = new ServerSocket(socket);
        System.out.println("Listening...");
        while (!end) {
            Socket socket = serverSocket.accept();
            InputStreamReader isr = new InputStreamReader(socket.getInputStream());
            PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
            int character;
            StringBuffer inputStrBuffer = new StringBuffer();
            while ((character = isr.read()) != 13) {
                inputStrBuffer.append((char) character);
            }
            System.out.println(inputStrBuffer.toString());
            String[] cmd; // = inputStrBuffer.toString().split(" ");
            String result = "YOUR REQUEST WAS NOT VALID JSON";
            if (inputStrBuffer.substring(0, 1).equals("{")) {
                nodeType = extractElement(inputStrBuffer.toString(), "node_type");
                if (sharedKey != null) {
                    if (validateSignature(extractElement(inputStrBuffer.toString(), "time_stamp"),
                            extractElement(inputStrBuffer.toString(), "signature"))) {
                        if ("Y".equalsIgnoreCase(extractElement(inputStrBuffer.toString(), "cmd_encoded")))
                            cmd = decryptCommand(extractElement(inputStrBuffer.toString(), "command"));
                        else
                            cmd = extractElement(inputStrBuffer.toString(), "command").split(" ");
                        result = getResult(cmd);
                    } else
                        result = "YOUR SIGNATURE DID NOT MATCH, CHECK SHARED KEY";
                } else {
                    cmd = extractElement(inputStrBuffer.toString(), "command").split(" ");
                    result = getResult(cmd);
                }
            }
            System.out.println(result);
            output.print(result);
            output.print((char) 13);
            output.close();
            isr.close();
            socket.close();
        }
        serverSocket.close();
        System.out.println("Shutting down.");
    } catch (Exception exception) {
        exception.printStackTrace();
    }
}

From source file:ca.uqac.info.monitor.BeepBeepMonitor.java

public static void main(String[] args) {
    int verbosity = 1, slowdown = 0, tcp_port = 0;
    boolean show_stats = false, to_stdout = false;
    String trace_filename = "", pipe_filename = "", event_name = "message";
    final MonitorFactory mf = new MonitorFactory();

    // In case we open a socket
    ServerSocket m_serverSocket = null;
    Socket m_connection = null;//from www.  j  a  v  a2s . c o m

    // Parse command line arguments
    Options options = setupOptions();
    CommandLine c_line = setupCommandLine(args, options);
    assert c_line != null;
    if (c_line.hasOption("verbosity")) {
        verbosity = Integer.parseInt(c_line.getOptionValue("verbosity"));
    }
    if (verbosity > 0) {
        showHeader();
    }
    if (c_line.hasOption("version")) {
        System.err.println("(C) 2008-2013 Sylvain Hall et al., Universit du Qubec  Chicoutimi");
        System.err.println("This program comes with ABSOLUTELY NO WARRANTY.");
        System.err.println("This is a free software, and you are welcome to redistribute it");
        System.err.println("under certain conditions. See the file COPYING for details.\n");
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("h")) {
        showUsage(options);
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("version")) {
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("slowdown")) {
        slowdown = Integer.parseInt(c_line.getOptionValue("slowdown"));
        if (verbosity > 0)
            System.err.println("Slowdown factor: " + slowdown + " ms");
    }
    if (c_line.hasOption("stats")) {
        show_stats = true;
    }
    if (c_line.hasOption("csv")) {
        // Will output data in CSV format to stdout
        to_stdout = true;
    }
    if (c_line.hasOption("eventname")) {
        // Set event name
        event_name = c_line.getOptionValue("eventname");
    }
    if (c_line.hasOption("t")) {
        // Read events from a trace
        trace_filename = c_line.getOptionValue("t");
    }
    if (c_line.hasOption("p")) {
        // Read events from a pipe
        pipe_filename = c_line.getOptionValue("p");
    }
    if (c_line.hasOption("k")) {
        // Read events from a TCP port
        tcp_port = Integer.parseInt(c_line.getOptionValue("k"));
    }
    if (!trace_filename.isEmpty() && !pipe_filename.isEmpty()) {
        System.err.println("ERROR: you must specify at most one of trace file or named pipe");
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    @SuppressWarnings("unchecked")
    List<String> remaining_args = c_line.getArgList();
    if (remaining_args.isEmpty()) {
        System.err.println("ERROR: no input formula specified");
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    // Instantiate the event notifier
    boolean notify = (verbosity > 0);
    EventNotifier en = new EventNotifier(notify);
    en.m_slowdown = slowdown;
    en.m_csvToStdout = to_stdout;
    // Create one monitor for each input file and add it to the notifier 
    for (String formula_filename : remaining_args) {
        try {
            String formula_contents = FileReadWrite.readFile(formula_filename);
            Operator op = Operator.parseFromString(formula_contents);
            op.accept(mf);
            Monitor mon = mf.getMonitor();
            Map<String, String> metadata = getMetadata(formula_contents);
            metadata.put("Filename", formula_filename);
            en.addMonitor(mon, metadata);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(ERR_IO);
        } catch (Operator.ParseException e) {
            System.err.println("Error parsing input formula");
            System.exit(ERR_PARSE);
        }
    }

    // Read trace and iterate
    // Opens file
    PipeReader pr = null;
    try {
        if (!pipe_filename.isEmpty()) {
            // We tell the pipe reader we read a pipe
            File f = new File(pipe_filename);
            if (verbosity > 0)
                System.err.println("Reading from pipe named " + f.getName());
            pr = new PipeReader(new FileInputStream(f), en, false);
        } else if (!trace_filename.isEmpty()) {
            // We tell the pipe reader we read a regular file
            File f = new File(trace_filename);
            if (verbosity > 0)
                System.err.println("Reading from file " + f.getName());
            pr = new PipeReader(new FileInputStream(f), en, true);
        } else if (tcp_port > 0) {
            // We tell the pipe reader we read from a socket
            if (verbosity > 0)
                System.err.println("Reading from TCP port " + tcp_port);
            m_serverSocket = new ServerSocket(tcp_port);
            m_connection = m_serverSocket.accept();
            pr = new PipeReader(m_connection.getInputStream(), en, false);
        } else {
            // We tell the pipe reader we read from standard input
            if (verbosity > 0)
                System.err.println("Reading from standard input");
            pr = new PipeReader(System.in, en, false);
        }
    } catch (FileNotFoundException ex) {
        // We print both trace and pipe since one of them must be empty
        System.err.println("ERROR: file not found " + trace_filename + pipe_filename);
        System.exit(ERR_IO);
    } catch (IOException e) {
        // Caused by socket error
        e.printStackTrace();
        System.exit(ERR_IO);
    }
    pr.setSeparator("<" + event_name + ">", "</" + event_name + ">");

    // Check parameters for the event notifier
    if (c_line.hasOption("no-trigger")) {
        en.m_notifyOnVerdict = false;
    } else {
        en.m_notifyOnVerdict = true;
    }
    if (c_line.hasOption("mirror")) {
        en.m_mirrorEventsOnStdout = true;
    }

    // Start event notifier
    en.reset();
    Thread th = new Thread(pr);
    long clock_start = System.nanoTime();
    th.start();
    try {
        th.join(); // Wait for thread to finish
    } catch (InterruptedException e1) {
        // Thread is finished
    }
    if (tcp_port > 0 && m_serverSocket != null) {
        // We opened a socket; now we close it
        try {
            m_serverSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    long clock_end = System.nanoTime();
    int ret_code = pr.getReturnCode();
    switch (ret_code) {
    case PipeReader.ERR_EOF:
        if (verbosity > 0)
            System.err.println("\nEnd of file reached");
        break;
    case PipeReader.ERR_EOT:
        if (verbosity > 0)
            System.err.println("\nEOT received on pipe: closing");
        break;
    case PipeReader.ERR_OK:
        // Do nothing
        break;
    default:
        // An error
        System.err.println("Runtime error");
        System.exit(ERR_RUNTIME);
        break;
    }
    if (show_stats) {
        if (verbosity > 0) {
            System.out.println("Messages:   " + en.m_numEvents);
            System.out.println("Time:       " + (int) (en.m_totalTime / 1000000f) + " ms");
            System.out.println("Clock time: " + (int) ((clock_end - clock_start) / 1000000f) + " ms");
            System.out.println("Max heap:   " + (int) (en.heapSize / 1048576f) + " MB");
        } else {
            // If stats are asked but verbosity = 0, only show time value
            // (both monitor and wall clock) 
            System.out.print((int) (en.m_totalTime / 1000000f));
            System.out.print(",");
            System.out.print((int) ((clock_end - clock_start) / 1000000f));
        }
    }
    System.exit(ERR_OK);
}