Example usage for java.net Socket getOutputStream

List of usage examples for java.net Socket getOutputStream

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream for this socket.

Usage

From source file:tap.Tap.java

/**
 * Usage:<BR> FIXME?//  ww w .  j  av  a2s.  c o  m
 *       java votebox.Tap [serial] [report address] [port]
 *
 * @param args      arguments to be used
 *
 * @throws RuntimeException if there is an issue parsing values, the port used is bad,
 *                          or there is an interruption in the process
 */
public static void main(String[] args) {

    IAuditoriumParams params = new AuditoriumParams("tap.conf");

    System.out.println(params.getReportAddress());

    String reportAddr;

    int serial;
    int port;
    String launchCode;

    /* See if there isn't a full argument set */
    if (args.length != 4) {

        int p = 0;

        /* Assign the default serial */
        serial = params.getDefaultSerialNumber();

        /* If the serial is still bad... */
        if (serial == -1) {

            /* Try the first of the given arguments */
            try {
                serial = Integer.parseInt(args[p]);
                p++;
            } catch (Exception e) {
                throw new RuntimeException(
                        "usage: Tap [serial] [report address] [port]\nExpected valid serial.");
            }
        }

        /* Assign the report address */
        reportAddr = params.getReportAddress();

        /* If no valid address... */
        if (reportAddr.length() == 0) {

            /* Try one of the given arguments (first or second, depending) */
            try {
                reportAddr = args[p];
                p++;
            } catch (Exception e) {
                throw new RuntimeException("usage: Tap [serial] [report address] [port]");
            }
        }

        /* Assign the port */
        //port = params.getPort();
        port = Integer.parseInt(args[p]);

        /* If the port is still bad... */
        if (port == -1) {

            /* Try one of the given arguments (first, second, or third, depending) */
            try {
                port = Integer.parseInt(args[p]);
            } catch (Exception e) {
                throw new RuntimeException("usage: Tap [serial] [report address] [port]\nExpected valid port.");
            }
        }

        launchCode = "0000000000";
    }

    /* If there is a full argument set... */
    else {

        /* Try to load up the args */
        try {
            serial = Integer.parseInt(args[0]);
            reportAddr = args[1];
            port = Integer.parseInt(args[2]);
            launchCode = args[3];
        } catch (Exception e) {
            throw new RuntimeException("usage: Tap [serial] [report address] [port]");
        }
    }

    try {

        /* Create a new socket address */
        System.out.println(reportAddr + port);
        InetSocketAddress addr = new InetSocketAddress(reportAddr, port);

        /* Loop until an exception or tap is started */
        while (true) {

            try {

                /* Try to establish a socket connection */
                Socket localCon = new Socket();
                localCon.connect(addr);

                /* Start the tap */
                (new Tap(serial, localCon.getOutputStream(), launchCode, params)).start();
                System.out.println("Connection successful to " + addr);
                break;
            } catch (IOException e) { /* If no good, retry */
                System.out.println("Connection failed: " + e.getMessage());
                System.out.println("Retry in 5 seconds...");
                Thread.sleep(5000);
            }
        }
    } catch (NumberFormatException e) {
        throw new RuntimeException(
                "usage: Tap [serial] [report address] [port]; where port is between 1 and 65335 & [serial] is a positive integer",
                e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

    /* TEST CODE */

    testMethod();

    /* END TEST CODE */

}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    System.setProperty("javax.net.ssl.keyStore", "lfkeystore2");
    System.setProperty("javax.net.ssl.keyStorePassword", "wshr.ut");

    SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    ServerSocket ss = ssf.createServerSocket(5432);
    while (true) {
        Socket s = ss.accept();
        SSLSession session = ((SSLSocket) s).getSession();
        Certificate[] cchain2 = session.getLocalCertificates();
        for (int i = 0; i < cchain2.length; i++) {
            System.out.println(((X509Certificate) cchain2[i]).getSubjectDN());
        }//w  w  w.  ja  va2 s.  c  o  m
        System.out.println("Peer host is " + session.getPeerHost());
        System.out.println("Cipher is " + session.getCipherSuite());
        System.out.println("Protocol is " + session.getProtocol());
        System.out.println("ID is " + new BigInteger(session.getId()));
        System.out.println("Session created in " + session.getCreationTime());
        System.out.println("Session accessed in " + session.getLastAccessedTime());

        PrintStream out = new PrintStream(s.getOutputStream());
        out.println("Hi");
        out.close();
        s.close();
    }

}

From source file:flink.iso8583.example.Client.java

public static void main(String[] args) throws Exception {
    Random rng = new Random(System.currentTimeMillis());
    log.debug("Reading config");
    mfact = ConfigParser.createFromClasspathConfig("flink/iso8583/example/config.xml");
    mfact.setAssignDate(true);/*from   w  w w.  j  a  va2s  .  c om*/
    mfact.setTraceNumberGenerator(new SimpleTraceGenerator((int) (System.currentTimeMillis() % 10000)));
    log.debug("Connecting to server");
    Socket sock = new Socket("localhost", 9999);
    //Send 10 messages, then wait for the responses
    Client reader = new Client(sock);
    reader.start();
    for (int i = 0; i < 10; i++) {
        IsoMessage req = mfact.newMessage(0x200);
        req.setValue(4, amounts[rng.nextInt(amounts.length)], IsoType.AMOUNT, 0);
        req.setValue(12, req.getObjectValue(7), IsoType.TIME, 0);
        req.setValue(13, req.getObjectValue(7), IsoType.DATE4, 0);
        req.setValue(15, req.getObjectValue(7), IsoType.DATE4, 0);
        req.setValue(17, req.getObjectValue(7), IsoType.DATE4, 0);
        req.setValue(37, new Long(System.currentTimeMillis() % 1000000), IsoType.NUMERIC, 12);
        req.setValue(41, data[rng.nextInt(data.length)], IsoType.ALPHA, 16);
        req.setValue(48, data[rng.nextInt(data.length)], IsoType.LLLVAR, 0);
        pending.put(req.getField(11).toString(), req);
        log.debug("Sending request " + req.getField(11));
        req.write(sock.getOutputStream(), 2);
    }
    log.debug("Waiting for responses");
    while (pending.size() > 0 && sock.isConnected()) {
        sleep(500);
    }
    reader.interrupt();
    sock.close();
    log.debug("DONE.");
}

From source file:j8583.example.Client.java

public static void main(String[] args) throws Exception {
    Random rng = new Random(System.currentTimeMillis());
    log.debug("Reading config");
    mfact = ConfigParser.createFromClasspathConfig("j8583/example/config.xml");
    mfact.setAssignDate(true);//from  w  w  w.j a v  a 2  s .co  m
    mfact.setTraceNumberGenerator(new SimpleTraceGenerator((int) (System.currentTimeMillis() % 10000)));
    System.err.println("Connecting to server");
    Socket sock = new Socket("localhost", 9999);
    // Send 10 messages, then wait for the responses
    Client client = new Client(sock);
    Thread reader = new Thread(client, "j8583-client");
    reader.start();
    for (int i = 0; i < 10; i++) {
        IsoMessage req = mfact.newMessage(0x200);
        req.setValue(4, amounts[rng.nextInt(amounts.length)], IsoType.AMOUNT, 0);
        req.setValue(12, req.getObjectValue(7), IsoType.TIME, 0);
        req.setValue(13, req.getObjectValue(7), IsoType.DATE4, 0);
        req.setValue(15, req.getObjectValue(7), IsoType.DATE4, 0);
        req.setValue(17, req.getObjectValue(7), IsoType.DATE4, 0);
        req.setValue(37, System.currentTimeMillis() % 1000000, IsoType.NUMERIC, 12);
        req.setValue(41, data[rng.nextInt(data.length)], IsoType.ALPHA, 16);
        req.setValue(48, data[rng.nextInt(data.length)], IsoType.LLLVAR, 0);
        pending.put(req.getField(11).toString(), req);
        System.err.println(String.format("Sending request %s", req.getField(11)));
        req.write(sock.getOutputStream(), 2);
    }
    log.debug("Waiting for responses");
    while (pending.size() > 0 && sock.isConnected()) {
        Thread.sleep(500);
    }
    client.stop();
    reader.interrupt();
    log.debug("DONE.");
}

From source file:cacheservice.CacheServer.java

/**
 * @param args the command line arguments
 *//*from  w ww  .  ja v  a2 s.  c  o m*/
public static void main(String[] args) {
    // COMUNICACIN CON EL CLIENTE
    ServerSocket serverSocket;
    Socket socketCliente;
    DataInputStream in; //Flujo de datos de entrada
    DataOutputStream out; //Flujo de datos de salida
    String mensaje;
    int laTengoenCache = 0;

    //COMUNICACIN CON EL INDEX
    ServerSocket serverSocketIndex;
    Socket socketIndex;
    DataOutputStream outIndex;
    ObjectInputStream inIndex;
    String mensajeIndex;

    try {
        serverSocket = new ServerSocket(4444);
        System.out.print("SERVIDOR CACHE ACTIVO a la espera de peticiones");

        //MIENTRAS PERMANEZCA ACTIVO EL SERVIDOR CACHE ESPERAR? POR PETICIONES DE LOS CLIENTES
        while (true) {
            socketCliente = serverSocket.accept();
            in = new DataInputStream(socketCliente.getInputStream()); //Entrada de los mensajes del cliente
            mensaje = in.readUTF(); //Leo el mensaje enviado por el cliente

            System.out.println("\nHe recibido del cliente: " + mensaje); //Muestro el mensaje recibido por el cliente
            //int particionBuscada = seleccionarParticion(mensaje, tamanoCache, numeroParticiones); //Busco la particin
            //double tamanoParticion = Math.ceil( (double)tamanoCache / (double)numeroParticiones);

            //Thread hilo = new Hilo(mensaje,particionBuscada,cache.GetTable(),(int) tamanoParticion);
            //hilo.start();

            //RESPUESTA DEL SERVIDOR CACHE AL CLIENTE
            out = new DataOutputStream(socketCliente.getOutputStream());
            String respuesta = "Respuesta para " + mensaje;
            if (laTengoenCache == 1) {
                out.writeUTF(respuesta);
                System.out.println("\nTengo la respuesta. He respondido al cliente: " + respuesta);
            } else {
                out.writeUTF("miss");
                out.close();
                in.close();
                socketCliente.close();

                System.out.println("\nNo tengo la respuesta.");

                //LEER RESPUESTA DEL SERVIDOR INDEX
                serverSocketIndex = new ServerSocket(6666);
                socketIndex = serverSocketIndex.accept();
                inIndex = new ObjectInputStream(socketIndex.getInputStream());
                JSONObject mensajeRecibidoIndex = (JSONObject) inIndex.readObject();

                System.out.println("He recibido del SERVIDOR INDEX: " + mensajeRecibidoIndex);

                //outIndex.close();
                inIndex.close();
                socketIndex.close();

            }

        }
    } catch (Exception e) {
        System.out.print(e.getMessage());
    }
}

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   www  .  j  a  va  2  s .  c  om
    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: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  ww. ja v a  2s.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:Main.java

public static void whois(String query, String server) throws IOException {
    Socket sock = new Socket(server, 43);
    int c = 0;/*w w w. j a va  2  s. c om*/

    OutputStream os = sock.getOutputStream();
    InputStream is = sock.getInputStream();
    query += "\r\n";
    os.write(query.getBytes("iso8859_1"));

    while (c != -1) {
        c = is.read();
        if (c != -1)
            System.out.println((char) c);
    }
}

From source file:Main.java

public static void writeNetSocketBytes(Socket socket, byte[] buffer, int len) throws Exception {
    OutputStream os = socket.getOutputStream();
    os.write(buffer, 0, len);/* w  ww . j a  v a  2 s.  co  m*/
    os.flush();
}

From source file:Main.java

public static void sendStopSignal(int port) {
    try {//www .  j  ava2s.c  o m
        Socket s = new Socket(InetAddress.getByName("127.0.0.1"), port);
        OutputStream out = s.getOutputStream();
        System.err.println("sending server stop request");
        out.write(("\r\n").getBytes());
        out.flush();
        s.close();
    } catch (Exception e) {
        // can happen when called twice by jvm shutdown hook
        System.err.println("stop monitor thread has terminated");
    }
}