Example usage for java.net ServerSocket accept

List of usage examples for java.net ServerSocket accept

Introduction

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

Prototype

public Socket accept() throws IOException 

Source Link

Document

Listens for a connection to be made to this socket and accepts it.

Usage

From source file:com.couragelabs.logging.LogAppenderTestFixture.java

/**
 * Use this method to test the appender. Run this first, then run
 * GlobalContextSocketAppender::main/*from  w w  w.j av a 2  s.  c o m*/
 *
 * @param args Program arguments. None are needed.
 * @throws java.lang.Exception if things go wrong
 */
@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    ServerSocket serverSocket = new ServerSocket(PORT);

    System.out.println("Starting listen loop.");
    while (true) {
        try {
            final Socket clientSocket = serverSocket.accept();
            System.out.println("Received client connection.");
            new Thread() {
                @Override
                public void run() {
                    ObjectInputStream i = null;
                    try {
                        i = new ObjectInputStream(clientSocket.getInputStream());
                        while (true) {
                            Object received = i.readObject();
                            System.out.println(ToStringBuilder.reflectionToString(received,
                                    ToStringStyle.SHORT_PREFIX_STYLE));
                            Thread.sleep(1000);
                        }
                    } catch (EOFException e) {
                        System.out.println("Client closed connection.");
                    } catch (Throwable t) {
                        t.printStackTrace();
                    } finally {
                        if (i != null) {
                            try {
                                i.close();
                            } catch (Throwable t) {
                                t.printStackTrace();
                            }
                        }
                    }
                }
            }.start();
            Thread.sleep(1000);
        } catch (Throwable t) {
            t.printStackTrace();
        }
        System.out.println("Next...");
    }

}

From source file:ChatServer.java

public static void main(String[] args) {
    // DeviceUpdater du = new DeviceUpdater();
    int id = 0;//from   ww w .j  a  va 2  s.c o m
    String host = "localhost";
    int port = 11001;
    if (args.length == 2) {
        host = args[0];
        port = Integer.valueOf(args[1]);
    }
    Socket sock;
    try {
        ServerSocket server = new ServerSocket(port);
        while (true) {
            // System.out.println("Server waiting for connects on port " + port);
            sock = server.accept();
            id++;
            ChatServer threadOfServer = new ChatServer(sock, id);
            threadOfServer.start();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:net.socket.bio.TimeServer.java

/**
 * @param args//from   ww w.  j  a  va 2s.c  o m
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    int port = 8089;
    if (args != null && args.length > 0) {

        try {
            port = Integer.valueOf(args[0]);
        } catch (NumberFormatException e) {
            // 
        }

    }
    ServerSocket server = null;
    try {
        server = new ServerSocket(port);
        System.out.println("The time server is start in port : " + port);
        Socket socket = null;
        while (true) {
            socket = server.accept();
            System.out.println("socket name" + socket);
            new Thread(new TimeServerHandler(socket)).start();
        }
    } finally {
        IOUtils.closeQuietly(server);
    }
}

From source file:LoopingSocketServer.java

public static void main(String args[]) throws Exception {
    ServerSocket servSocket;
    Socket fromClientSocket;/* www . j  a  v a 2 s.c o m*/
    int cTosPortNumber = 1777;
    String str;

    servSocket = new ServerSocket(cTosPortNumber);
    System.out.println("Waiting for a connection on " + cTosPortNumber);
    fromClientSocket = servSocket.accept();
    System.out.println("fromClientSocket accepted");

    ObjectOutputStream oos = new ObjectOutputStream(fromClientSocket.getOutputStream());

    ObjectInputStream ois = new ObjectInputStream(fromClientSocket.getInputStream());

    while ((str = (String) ois.readObject()) != null) {
        System.out.println("The message from client:  " + str);

        if (str.equals("bye")) {
            oos.writeObject("bye bye");
            break;
        } else {
            str = "Server returns " + str;
            oos.writeObject(str);
        }

    }
    oos.close();
    fromClientSocket.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    ServerSocket serverSocket = new ServerSocket(12900, 100, InetAddress.getByName("localhost"));
    System.out.println("Server started  at:  " + serverSocket);

    while (true) {
        System.out.println("Waiting for a  connection...");

        final Socket activeSocket = serverSocket.accept();

        System.out.println("Received a  connection from  " + activeSocket);
        Runnable runnable = () -> handleClientRequest(activeSocket);
        new Thread(runnable).start(); // start a new thread
    }/*from   www  . ja  v  a 2  s . co m*/
}

From source file:MiniCluster.java

/**
 * Runs the {@link MiniAccumuloCluster} given a -p argument with a property file. Establishes a shutdown port for asynchronous operation.
 * /*w w  w .  ja  v a 2  s  . c  o  m*/
 * @param args
 *          An optional -p argument can be specified with the path to a valid properties file.
 */
public static void main(String[] args) throws Exception {
    Opts opts = new Opts();
    opts.parseArgs(MiniCluster.class.getName(), args);

    if (opts.printProps) {
        printProperties();
        System.exit(0);
    }

    int shutdownPort = 4445;

    final File miniDir;

    if (opts.prop.containsKey(DIRECTORY_PROP))
        miniDir = new File(opts.prop.getProperty(DIRECTORY_PROP));
    else
        miniDir = Files.createTempDir();

    String rootPass = opts.prop.containsKey(ROOT_PASSWORD_PROP) ? opts.prop.getProperty(ROOT_PASSWORD_PROP)
            : "secret";
    String instanceName = opts.prop.containsKey(INSTANCE_NAME_PROP) ? opts.prop.getProperty(INSTANCE_NAME_PROP)
            : "accumulo";
    MiniAccumuloConfig config = new MiniAccumuloConfig(miniDir, instanceName, rootPass);

    if (opts.prop.containsKey(NUM_T_SERVERS_PROP))
        config.setNumTservers(Integer.parseInt(opts.prop.getProperty(NUM_T_SERVERS_PROP)));
    if (opts.prop.containsKey(ZOO_KEEPER_PORT_PROP))
        config.setZooKeeperPort(Integer.parseInt(opts.prop.getProperty(ZOO_KEEPER_PORT_PROP)));
    //    if (opts.prop.containsKey(JDWP_ENABLED_PROP))
    //      config.setJDWPEnabled(Boolean.parseBoolean(opts.prop.getProperty(JDWP_ENABLED_PROP)));
    //    if (opts.prop.containsKey(ZOO_KEEPER_MEMORY_PROP))
    //      setMemoryOnConfig(config, opts.prop.getProperty(ZOO_KEEPER_MEMORY_PROP), ServerType.ZOOKEEPER);
    //    if (opts.prop.containsKey(TSERVER_MEMORY_PROP))
    //      setMemoryOnConfig(config, opts.prop.getProperty(TSERVER_MEMORY_PROP), ServerType.TABLET_SERVER);
    //    if (opts.prop.containsKey(MASTER_MEMORY_PROP))
    //      setMemoryOnConfig(config, opts.prop.getProperty(MASTER_MEMORY_PROP), ServerType.MASTER);
    //    if (opts.prop.containsKey(DEFAULT_MEMORY_PROP))
    //      setMemoryOnConfig(config, opts.prop.getProperty(DEFAULT_MEMORY_PROP));
    //    if (opts.prop.containsKey(SHUTDOWN_PORT_PROP))
    //      shutdownPort = Integer.parseInt(opts.prop.getProperty(SHUTDOWN_PORT_PROP));

    Map<String, String> siteConfig = new HashMap<String, String>();
    for (Map.Entry<Object, Object> entry : opts.prop.entrySet()) {
        String key = (String) entry.getKey();
        if (key.startsWith("site."))
            siteConfig.put(key.replaceFirst("site.", ""), (String) entry.getValue());
    }

    config.setSiteConfig(siteConfig);

    final MiniAccumuloCluster accumulo = new MiniAccumuloCluster(config);

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                accumulo.stop();
                FileUtils.deleteDirectory(miniDir);
                System.out.println("\nShut down gracefully on " + new Date());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });

    accumulo.start();

    printInfo(accumulo, shutdownPort);

    // start a socket on the shutdown port and block- anything connected to this port will activate the shutdown
    ServerSocket shutdownServer = new ServerSocket(shutdownPort);
    shutdownServer.accept();

    System.exit(0);
}

From source file:slideshow.server.App.java

/**
 * Initializes server and creates threads
 * //from www  .  jav  a2  s. c om
 * @param args 
 * @throws java.lang.InterruptedException 
 * @throws java.io.IOException 
 */
public static void main(String[] args) throws InterruptedException, IOException, JSONException {
    System.out.print("Testing sending a picture");
    Socket sSocket = null;
    Calendar cal = new GregorianCalendar();
    int today = cal.get(Calendar.DAY_OF_MONTH);
    int month = cal.get(Calendar.MONTH) + 1;
    int year = cal.get(Calendar.YEAR);

    holderDate ticker = new holderDate();
    ticker.setDay(today);
    ticker.setMonth(month);
    ticker.setYear(year);
    ticker.setNewPicture("");
    String APIdate = "";

    try {
        ServerSocket serverSocket = new ServerSocket(6001);
        System.out.println("Waiting for connection...");
        sSocket = serverSocket.accept();
        OutputStream outputStream = sSocket.getOutputStream();

        while (true) {
            ticker = getNextDate(ticker);

            APIdate = ticker.getNewPicture();

            String APIStream = getAPIPicture(APIdate);

            PrintWriter out = new PrintWriter(sSocket.getOutputStream(), true);
            String inputLine;

            out.println(APIStream);

            Thread.sleep(10000);
            /* ImageInputStream imageInput = ImageIO.createImageInputStream(APIStream);
             BufferedImage img = ImageIO.read(imageInput);
             ByteArrayOutputStream pictureOutput = new ByteArrayOutputStream();
             ImageIO.write(img, "jpg", pictureOutput);
                     
             byte[] size = ByteBuffer.allocate(4).putInt(pictureOutput.size()).array();
             outputStream.write(size);
             outputStream.write(pictureOutput.toByteArray());
             outputStream.flush();*/

            if (ticker.getYear() == 1999) {
                break;
            }
            System.out.println(APIStream);
        }
        sSocket.close();

    } catch (IOException es) {
        System.out.println(es.getMessage());
    }

}

From source file:org.msec.LogsysProxy.java

public static void main(String[] args) {

    try {/*from ww  w .  ja  v a 2 s  . co  m*/
        Options options = new Options();
        Option option = new Option("c", "conf", true, "configuration filename");
        option.setRequired(true);
        options.addOption(option);

        option = new Option("h", "help", false, "show help");
        options.addOption(option);

        CommandLineParser parser = new GnuParser();
        CommandLine commandLine = null;

        try {
            commandLine = parser.parse(options, args);
        } catch (ParseException e) {
            System.out.println("Parse command line failed.");
            e.printStackTrace();
            return;
        }

        if (commandLine.hasOption('h')) {
            new HelpFormatter().printHelp("LogsysProxy", options, true);
            return;
        }

        //
        String conFilename = commandLine.getOptionValue('c');
        String userdir = System.getProperty("user.dir");
        Properties props = new Properties();
        InputStream in = new FileInputStream(conFilename);
        props.load(in);
        in.close();

        PropertyConfigurator.configure("conf/log4j.properties");
        Class.forName("com.mysql.jdbc.Driver");

        //: 30150
        int listenPort = Integer.parseInt(props.getProperty("listen", "30150"));
        ServerSocket serverSocket = new ServerSocket(listenPort);
        Socket socket = null;

        logger.info("Logsys Proxy Started.");
        //, 
        while (true) {
            socket = serverSocket.accept();

            InetAddress address = socket.getInetAddress();
            logger.info("Request coming ... " + address.getHostAddress());
            ServerThread serverThread = new ServerThread(socket, conFilename, props);
            serverThread.start();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:Cache.Servidor.java

public static void main(String[] args) throws IOException, ClassNotFoundException {
    // Se calcula el tamao de las particiones del cache
    // de manera que la relacin sea
    // 25% Esttico y 75% Dinmico,
    // siendo la porcin dinmica particionada en 3 partes.

    Lector l = new Lector(); // Obtener tamao total del cache.
    int tamCache = l.leerTamCache("config.txt");
    //===================================
    int tamCaches = 0;
    if (tamCache % 4 == 0) { // Asegura que el nro sea divisible por 4.
        tamCaches = tamCache / 4;/*from   ww w .  ja v a 2 s  . c  o m*/
    } else { // Si no, suma para que lo sea.
        tamCaches = (tamCache - (tamCache) % 4 + 4) / 4;
    } // y divide por 4.

    System.out.println("Tamao total Cache: " + (int) tamCache); // imprimir tamao cache.
    System.out.println("Tamao particiones y parte esttica: " + tamCaches); // imprimir tamao particiones.
    //===================================

    lru_cache1 = new LRUCache(tamCaches); //Instanciar atributos.

    lru_cache2 = new LRUCache(tamCaches);
    lru_cache3 = new LRUCache(tamCaches);
    cestatico = new CacheEstatico(tamCaches);
    cestatico.addEntryToCache("query3", "respuesta cacheEstatico a query 3");
    cestatico.addEntryToCache("query7", "respuesta cacheEstatico a query 7");

    try {
        ServerSocket servidor = new ServerSocket(4500); // Crear un servidor en pausa hasta que un cliente llegue.
        while (true) {
            Socket clienteNuevo = servidor.accept();// Si llega se acepta.
            // Queda en pausa otra vez hasta que un objeto llegue.
            ObjectInputStream entrada = new ObjectInputStream(clienteNuevo.getInputStream());

            System.out.println("Objeto llego");
            //===================================
            Cache1 hilox1 = new Cache1(); // Instanciar hebras.
            Cache2 hilox2 = new Cache2();
            Cache3 hilox3 = new Cache3();

            // Leer el objeto, es un String.
            JSONObject request = (JSONObject) entrada.readObject();
            String b = (String) request.get("busqueda");

            //*************************Actualizar CACHE**************************************
            int actualizar = (int) request.get("actualizacion");
            // Si vienen el objeto que llego viene del Index es que va a actualizar el cache
            if (actualizar == 1) {
                int lleno = cestatico.lleno();
                if (lleno == 0) {
                    cestatico.addEntryToCache((String) request.get("busqueda"),
                            (String) request.get("respuesta"));
                } else {
                    // si el cache estatico esta lleno
                    //agrego l cache dinamico

                    if (hash(b) % 3 == 0) {
                        lru_cache1.addEntryToCache((String) request.get("busqueda"),
                                (String) request.get("respuesta"));
                    } else {
                        if (hash(b) % 3 == 1) {
                            lru_cache2.addEntryToCache((String) request.get("busqueda"),
                                    (String) request.get("respuesta"));

                        } else {
                            lru_cache3.addEntryToCache((String) request.get("busqueda"),
                                    (String) request.get("respuesta"));

                        }
                    }

                }
            } //***************************************************************
            else {

                // Para cada request del arreglo se distribuye
                // en Cache 1 2 o 3 segn su hash.
                JSONObject respuesta = new JSONObject();
                if (hash(b) % 3 == 0) {
                    respuesta = hilox1.fn(request); //Y corre la funcin de una hebra.
                } else {
                    if (hash(b) % 3 == 1) {
                        respuesta = hilox2.fn(request);
                    } else {
                        respuesta = hilox3.fn(request);
                    }
                }

                //RESPONDER DESDE EL SERVIDOR
                ObjectOutputStream resp = new ObjectOutputStream(clienteNuevo.getOutputStream());// obtengo el output del cliente para mandarle un msj
                resp.writeObject(respuesta);
                System.out.println("msj enviado desde el servidor");

                //clienteNuevo.close();
                //servidor.close();
            }

        }
    } catch (IOException ex) {
        Logger.getLogger(Servidor.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:SimpleSocketServer.java

  public static void main(String args[]) throws Exception {
  ServerSocket serverSocket;
  int portNumber = 1777;
  Socket socket;/*from w w  w.j a  va2s.c  o m*/
  String str;

  str = " <?xml version=\"1.0\" encoding=\"UTF-8\"?>";
  str += "<ticketRequest><customer custID=\"1\">";
  str += "</ticketRequest>";

  serverSocket = new ServerSocket(portNumber);

  System.out.println("Waiting for a connection on " + portNumber);

  socket = serverSocket.accept();

  ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

  oos.writeObject(str);

  oos.close();

  socket.close();

}