Example usage for java.net ServerSocket ServerSocket

List of usage examples for java.net ServerSocket ServerSocket

Introduction

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

Prototype

public ServerSocket(int port) throws IOException 

Source Link

Document

Creates a server socket, bound to the specified port.

Usage

From source file:Server_socket.java

public static void main(String argv[]) throws Exception {

    int puerto = Integer.parseInt(argv[0]);
    //String username = argv[1];
    //String password = argv[2];
    String clientformat;/*from w ww.j  av a 2  s.  c o  m*/
    String clientdata;
    String clientresult;
    String clientresource;
    String url_login = "http://localhost:3000/users/sign_in";

    ServerSocket welcomeSocket = new ServerSocket(puerto);

    /*HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url_login);
            
            
      // Add your data
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
      // nameValuePairs.add(new BasicNameValuePair("utf8", Character.toString('\u2713')));
      nameValuePairs.add(new BasicNameValuePair("username", username));
      nameValuePairs.add(new BasicNameValuePair("password", password));
      // nameValuePairs.add(new BasicNameValuePair("commit", "Sign in"));
      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            
      // Execute HTTP Post Request
      HttpResponse response = httpClient.execute(httpPost);
      String ret = EntityUtils.tostring(response.getEntity());
       System.out.println(ret);
            
            
    */ while (true) {
        Socket connectionSocket = welcomeSocket.accept();

        BufferedReader inFromClient = new BufferedReader(
                new InputStreamReader(connectionSocket.getInputStream()));
        clientformat = inFromClient.readLine();
        System.out.println("FORMAT: " + clientformat);
        BufferedReader inFromClient1 = new BufferedReader(
                new InputStreamReader(connectionSocket.getInputStream()));
        clientdata = inFromClient1.readLine();
        System.out.println("DATA: " + clientdata);
        BufferedReader inFromClient2 = new BufferedReader(
                new InputStreamReader(connectionSocket.getInputStream()));
        clientresult = inFromClient2.readLine();
        System.out.println("RESULT: " + clientresult);
        BufferedReader inFromClient3 = new BufferedReader(
                new InputStreamReader(connectionSocket.getInputStream()));
        clientresource = inFromClient3.readLine();
        System.out.println("RESOURCE: " + clientresource);
        System.out.println("no pasas de aqui");

        String url = "http://localhost:3000/" + clientresource + "/" + clientdata + "." + clientformat;
        System.out.println(url);
        try (InputStream is = new URL(url).openStream()) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));

            StringBuilder sb = new StringBuilder();
            int cp;
            while ((cp = rd.read()) != -1) {
                sb.append((char) cp);
            }
            String stb = sb.toString();
            System.out.println("estas aqui");

            String output = null;
            String jsonText = stb;

            output = jsonText.replace("[", "").replace("]", "");
            JSONObject json = new JSONObject(output);

            System.out.println(json.toString());
            System.out.println("llegaste al final");
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            outToClient.writeBytes(json.toString());

        }

        connectionSocket.close();
    }
}

From source file:guardar.en.base.de.datos.MainServidor.java

public static void main(String[] args)
        throws ParserConfigurationException, SAXException, IOException, ClassNotFoundException {

    Mongo mongo = new Mongo("localhost", 27017);

    // nombre de la base de datos
    DB database = mongo.getDB("paginas");
    // coleccion de la db
    DBCollection collection = database.getCollection("indice");
    DBCollection collection_textos = database.getCollection("tabla");
    ArrayList<String> lista_textos = new ArrayList();

    try {/* ww w  .j av a  2s .com*/
        ServerSocket servidor = new ServerSocket(4545); // Crear un servidor en pausa hasta que un cliente llegue.
        while (true) {
            String aux = new String();
            lista_textos.clear();
            Socket clienteNuevo = servidor.accept();// Si llega se acepta.
            // Queda en pausa otra vez hasta que un objeto llegue.
            ObjectInputStream entrada = new ObjectInputStream(clienteNuevo.getInputStream());

            JSONObject request = (JSONObject) entrada.readObject();
            String b = (String) request.get("id");
            //hacer una query a la base de datos con la palabra que se quiere obtener

            BasicDBObject query = new BasicDBObject("palabra", b);
            DBCursor cursor = collection.find(query);
            ArrayList<DocumentosDB> lista_doc = new ArrayList<>();
            // de la query tomo el campo documentos y los agrego a una lista
            try {
                while (cursor.hasNext()) {
                    //System.out.println(cursor.next());
                    BasicDBList campo_documentos = (BasicDBList) cursor.next().get("documentos");
                    // en el for voy tomando uno por uno los elementos en el campo documentos
                    for (Iterator<Object> it = campo_documentos.iterator(); it.hasNext();) {
                        BasicDBObject dbo = (BasicDBObject) it.next();
                        //DOC tiene id y frecuencia
                        DocumentosDB doc = new DocumentosDB();
                        doc.makefn2(dbo);
                        //int id = (int)doc.getId_documento();
                        //int f = (int)doc.getFrecuencia();

                        lista_doc.add(doc);

                        //*******************************************

                        //********************************************

                        //QUERY A LA COLECCION DE TEXTOS
                        /* BasicDBObject query_textos = new BasicDBObject("id", doc.getId_documento());//query
                         DBCursor cursor_textos = collection_textos.find(query_textos);
                         try {
                        while (cursor_textos.hasNext()) {
                                    
                                    
                            DBObject obj = cursor_textos.next();
                                
                            String titulo = (String) obj.get("titulo");
                            titulo = titulo + "\n\n";
                            String texto = (String) obj.get("texto");
                                
                            String texto_final = titulo + texto;
                            aux = texto_final;
                            lista_textos.add(texto_final);
                        }
                         } finally {
                        cursor_textos.close();
                         }*/
                        //System.out.println(doc.getId_documento());
                        //System.out.println(doc.getFrecuencia());

                    } // end for

                } //end while query

            } finally {
                cursor.close();
            }

            // ordeno la lista de menor a mayor
            Collections.sort(lista_doc, new Comparator<DocumentosDB>() {

                @Override
                public int compare(DocumentosDB o1, DocumentosDB o2) {
                    //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
                    return o1.getFrecuencia().compareTo(o2.getFrecuencia());
                }
            });
            int tam = lista_doc.size() - 1;
            for (int j = tam; j >= 0; j--) {

                BasicDBObject query_textos = new BasicDBObject("id",
                        (int) lista_doc.get(j).getId_documento().intValue());//query
                DBCursor cursor_textos = collection_textos.find(query_textos);// lo busco
                try {
                    while (cursor_textos.hasNext()) {

                        DBObject obj = cursor_textos.next();
                        String titulo = "*******************************";
                        titulo += (String) obj.get("titulo");
                        int f = (int) lista_doc.get(j).getFrecuencia().intValue();
                        String strinf = Integer.toString(f);
                        titulo += "******************************* frecuencia:" + strinf;
                        titulo = titulo + "\n\n";

                        String texto = (String) obj.get("texto");

                        String texto_final = titulo + texto + "\n\n";
                        aux = aux + texto_final;
                        //lista_textos.add(texto_final);
                    }
                } finally {
                    cursor_textos.close();
                }

            }

            //actualizar el cache
            try {
                Socket cliente_cache = new Socket("localhost", 4500); // nos conectamos con el servidor
                ObjectOutputStream mensaje_cache = new ObjectOutputStream(cliente_cache.getOutputStream()); // get al output del servidor, que es cliente : socket del cliente q se conecto al server
                JSONObject actualizacion_cache = new JSONObject();
                actualizacion_cache.put("actualizacion", 1);
                actualizacion_cache.put("busqueda", b);
                actualizacion_cache.put("respuesta", aux);
                mensaje_cache.writeObject(actualizacion_cache); // envio el msj al servidor
            } catch (Exception ex) {

            }

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

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

}

From source file:Server.java

public static void main(String args[]) {
    ServerSocket serverSocket = null;

    Utilities.printMsg("creating server socket");

    try {//from   w  ww. j ava 2  s  .  c  o  m
        serverSocket = new ServerSocket(4444);
    } catch (IOException e) {
        System.err.println("Unable to create server socket, " + e);
        System.exit(1);
    }

    Utilities.printMsg("accepting client connections");

    while (true) {
        try {
            Socket clientSocket = serverSocket.accept();
            new Client(clientSocket).start();
        } catch (IOException e) {
            System.err.println("Unable to accept socket connection, " + e);
            System.exit(1);
        }
    }
}

From source file:Bounce.java

/**
 * The main method.//from w ww . j  av  a  2 s .  c  o m
 */

public static void main(String[] args) {
    if (args.length < 3) {
        printUsage();
        System.exit(1);
    }

    int localPort;
    try {
        localPort = Integer.parseInt(args[0]);
    } catch (NumberFormatException e) {
        System.err.println("Bad local port value: " + args[0]);
        printUsage();
        System.exit(2);
        return;
    }

    String hostname = args[1];

    int remotePort;
    try {
        remotePort = Integer.parseInt(args[2]);
    } catch (NumberFormatException e) {
        System.err.println("Bad remote port value: " + args[2]);
        printUsage();
        System.exit(3);
        return;
    }

    boolean shouldLog = args.length > 3 ? Boolean.valueOf(args[3]).booleanValue() : false;
    int numConnections = 0;

    try {
        ServerSocket ssock = new ServerSocket(localPort);
        while (true) {
            Socket incomingSock = ssock.accept();
            Socket outgoingSock = new Socket(hostname, remotePort);
            numConnections++;

            InputStream incomingIn = incomingSock.getInputStream();
            InputStream outgoingIn = outgoingSock.getInputStream();
            OutputStream incomingOut = incomingSock.getOutputStream();
            OutputStream outgoingOut = outgoingSock.getOutputStream();

            if (shouldLog) {
                String incomingLogName = "in-log-" + incomingSock.getInetAddress().getHostName() + "("
                        + localPort + ")-" + numConnections + ".dat";
                String outgoingLogName = "out-log-" + hostname + "(" + remotePort + ")-" + numConnections
                        + ".dat";
                OutputStream incomingLog = new FileOutputStream(incomingLogName);
                incomingOut = new MultiOutputStream(incomingOut, incomingLog);
                OutputStream outgoingLog = new FileOutputStream(outgoingLogName);
                outgoingOut = new MultiOutputStream(outgoingOut, outgoingLog);
            }

            PumpThread t1 = new PumpThread(incomingIn, outgoingOut);
            PumpThread t2 = new PumpThread(outgoingIn, incomingOut);
            t1.start();
            t2.start();
        }
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(3);
    }
}

From source file:WriteObjectsFromSocket.java

public static void main(String args[]) {
    Socket rs;/*from ww  w  .  ja v  a  2 s .  c o  m*/
    ServerSocket s;
    int PortNumber = 2000; // Fixed port
    boolean acceptLoop = true;
    ReaderWriter readerwriter = null;
    System.out.println("WriteFileFromSocket Running");
    // ////////////////////////////////////////////////////////////////
    // Open a socket on this server and listen for a connection
    // Look for data if we get here that is requests
    // ////////////////////////////////////////////////////////////////
    try {
        System.out.println("Waiting to accept connection");
        s = new ServerSocket(PortNumber);
    } catch (Exception e) {
        System.out.println("Unable to open port" + PortNumber);
        return;
    }
    while (acceptLoop) {
        try {
            rs = s.accept(); // Accept connections
        } catch (Exception e) {
            System.out.println("Accept failed port" + PortNumber);
            return;
        }
        readerwriter = new ReaderWriter(rs); // Start a thread to read the input
    }
}

From source file:ComplexCompany.java

public static void main(String args[]) throws Exception {
    ServerSocket servSocket;/*from   w  ww.ja va2 s .com*/
    Socket fromClientSocket;
    int cTosPortNumber = 1777;
    String str;
    ComplexCompany comp;

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

    fromClientSocket = servSocket.accept();

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

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

    while ((comp = (ComplexCompany) ois.readObject()) != null) {
        comp.printCompanyObject();

        oos.writeObject("bye bye");
        break;
    }
    oos.close();

    fromClientSocket.close();
}

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;//  w w  w .  j a  va 2s.  co 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:mecard.MetroService.java

public static void main(String[] args) {
    // First get the valid options
    Options options = new Options();
    // add t option c to config directory true=arg required.
    options.addOption("c", true,
            "configuration file directory path, include all sys dependant dir seperators like '/'.");
    // add t option c to config directory true=arg required.
    options.addOption("v", false, "Metro server version information.");
    try {/*  ww  w .j  av a 2 s .  c o m*/
        // parse the command line.
        CommandLineParser parser = new BasicParser();
        CommandLine cmd;
        cmd = parser.parse(options, args);
        if (cmd.hasOption("v")) {
            System.out.println("Metro (MeCard) server version " + PropertyReader.VERSION);
        }
        // get c option value
        String configDirectory = cmd.getOptionValue("c");
        PropertyReader.setConfigDirectory(configDirectory);
    } catch (ParseException ex) {
        //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println(
                new Date() + "Unable to parse command line option. Please check your service configuration.");
        System.exit(799);
    }

    Properties properties = PropertyReader.getProperties(ConfigFileTypes.ENVIRONMENT);
    String portString = properties.getProperty(LibraryPropertyTypes.METRO_PORT.toString(), defaultPort);

    try {
        int port = Integer.parseInt(portString);
        serverSocket = new ServerSocket(port);
    } catch (IOException ex) {
        String msg = " Could not listen on port: " + portString;
        //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex);
        System.out.println(new Date() + msg + ex.getMessage());
    } catch (NumberFormatException ex) {
        String msg = "Could not parse port number defined in configuration file.";
        //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex);
        System.out.println(new Date() + msg + ex.getMessage());
    }

    while (listening) {
        try {
            new SocketThread(serverSocket.accept()).start();
        } catch (IOException ex) {
            String msg = "unable to start server socket; either accept or start failed.";
            //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex);
            System.out.println(new Date() + msg);
        }
    }
    try {
        serverSocket.close();
    } catch (IOException ex) {
        String msg = "failed to close the server socket.";
        //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex);
        System.out.println(new Date() + msg);
    }
}

From source file:ezbake.local.accumulo.LocalAccumulo.java

public static void main(String args[]) throws Exception {
    Logger logger = LoggerFactory.getLogger(LocalAccumulo.class);
    final File accumuloDirectory = Files.createTempDir();

    int shutdownPort = 4445;
    MiniAccumuloConfig config = new MiniAccumuloConfig(accumuloDirectory, "strongpassword");
    config.setZooKeeperPort(12181);//ww w.  j  a v  a2  s .c o  m

    final MiniAccumuloCluster accumulo = new MiniAccumuloCluster(config);

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

    accumulo.start();

    printInfo(accumulo, shutdownPort);

    if (args.length > 0) {
        logger.info("Adding the following authorizations: {}", Arrays.toString(args));
        Authorizations auths = new Authorizations(args);
        Instance inst = new ZooKeeperInstance(accumulo.getConfig().getInstanceName(), accumulo.getZooKeepers());
        Connector client = inst.getConnector("root", new PasswordToken(accumulo.getConfig().getRootPassword()));
        logger.info("Connected...");
        client.securityOperations().changeUserAuthorizations("root", auths);
        logger.info("Auths updated");
    }

    // 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:com.biggerbytes.scheduleupdates.Main.java

/**
 * /*  w w  w .  j  a v a 2  s .com*/
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF); // In order to remove all the log warnings, THANK GOD IT IS THAT SIMPLE
    final int PORT = 25565;
    ServerSocket serverSocket = null;

    // Logger initialization 
    if (LOG) {
        fh = new FileHandler("serv_log.log", true); //It will create a new file everytime we start the server because the previous log is locked, I am not really sure where to close the handler.
        logger.addHandler(fh);
        SimpleFormatter formatter = new SimpleFormatter();
        fh.setFormatter(formatter);
    }
    //        /* Dummy Test */
    //        List<Byte> command = new ArrayList<>();
    //        command.add(CommandConstants.SCEHDULES_HEADER);
    //        command.add(CommandConstants.ADD_SUB_DUMMY);
    //        command.add((byte) 24);
    //        command.addAll(Arrays.asList(ArrayUtils.toObject("05".getBytes())));
    //        command.addAll(Arrays.asList(ArrayUtils.toObject("20.03.2016".getBytes())));
    //        command.addAll(Arrays.asList(ArrayUtils.toObject(" ".getBytes())));
    //        System.out.println("Size is " + command.size());
    //        byte[] commandArr = new byte[command.size()];
    //        for (int i = 0; i < commandArr.length; ++i)
    //            commandArr[i] = command.get(i);
    //        CommandProcessor.executeCommand(commandArr);
    /* Dummy Test End - TESTED, IT WORKS*/

    /* Dummy removal */
    //        byte[] remvCommand = new byte[3];
    //        remvCommand[0] = CommandConstants.SCEHDULES_HEADER;
    //        remvCommand[1] = CommandConstants.REMOVE_ALL_DUMMIES_FROM_ID;
    //        remvCommand[2] = (byte) 24;
    //        
    //        CommandProcessor.executeCommand(remvCommand);
    //        /* Dummy removal end - TESTED, WORKS*/

    try {
        serverSocket = new ServerSocket(PORT);
        initDataRefreshThread();
        infoReadThread.start();
    } catch (Exception e) {
        if (LOG)
            logger.info("Couldn't listen on port " + PORT);
        System.exit(-1);
    }

    new CreateClientThread().start(); //Setup thread for creating threads for clients

    while (true) {
        System.out.println("waiting");
        if (LOG)
            logger.info("Waiting for a client."); //TODO wait for the server to finish loading data then start waiting for a client
        Socket clientSocket = serverSocket.accept();
        clientsQ.add(clientSocket);
    }
}