List of usage examples for java.net Socket getInputStream
public InputStream getInputStream() throws IOException
From source file:Main.java
public static void main(String args[]) throws Exception { SocketFactory factory = SSLSocketFactory.getDefault(); Socket socket = factory.createSocket("127.0.0.1", 8080); OutputStream outputStream = socket.getOutputStream(); PrintWriter out = new PrintWriter(outputStream); out.print("GET / HTTP/1.0\r\n\r\n"); out.flush();/*from w w w . j a v a2 s . c o m*/ InputStream inputStream = socket.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader in = new BufferedReader(inputStreamReader); String line; while ((line = in.readLine()) != null) { System.out.println(line); } out.close(); in.close(); socket.close(); }
From source file:com.ccc.nhr.test1.NhrSocket.java
public static void main(String args[]) throws IOException, SQLException, ClassNotFoundException { final String host = "192.168.16.146"; final int portNumber = 10010; System.out.println("Creating socket to '" + host + "' on port " + portNumber); Socket socket = new Socket(host, portNumber); final NhrDataService nhrConnection = new NhrConnectionBuilder(socket) .withInputBufferedReader(new BufferedReader(new InputStreamReader(socket.getInputStream()))) .withDataInputStream(new DataInputStream(socket.getInputStream())) .withDataOutputStream(new DataOutputStream(socket.getOutputStream())).build(); ReceiverThread receiverThread = new ReceiverThread(); receiverThread.setNhrConnection(nhrConnection); receiverThread.start();/* www . ja va2 s . c om*/ SenderThread senderThread = new SenderThread(); senderThread.setNhrConnection(nhrConnection); senderThread.start(); }
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;// ww w . j a v a2 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:com.googlecode.shutdownlistener.ShutdownUtility.java
public static void main(String[] args) throws Exception { final ShutdownConfiguration config = ShutdownConfiguration.getInstance(); final String command; if (args.length > 0) { command = args[0];// w ww . j ava 2 s .co m } else { command = config.getStatusCommand(); } System.out.println("Calling " + config.getHost() + ":" + config.getPort() + " with command: " + command); final InetAddress hostAddress = InetAddress.getByName(config.getHost()); final Socket shutdownConnection = new Socket(hostAddress, config.getPort()); try { shutdownConnection.setSoTimeout(5000); final BufferedReader reader = new BufferedReader( new InputStreamReader(shutdownConnection.getInputStream())); final PrintStream writer = new PrintStream(shutdownConnection.getOutputStream()); try { writer.println(command); writer.flush(); while (true) { final String line = reader.readLine(); if (line == null) { break; } System.out.println(line); } } finally { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(writer); } } finally { try { shutdownConnection.close(); } catch (IOException ioe) { } } }
From source file:ComplexCompany.java
public static void main(String args[]) throws Exception { Socket socket1; int portNumber = 1777; String str = ""; socket1 = new Socket(InetAddress.getLocalHost(), portNumber); ObjectInputStream ois = new ObjectInputStream(socket1.getInputStream()); ObjectOutputStream oos = new ObjectOutputStream(socket1.getOutputStream()); ComplexCompany comp = new ComplexCompany("A"); ComplexEmployee emp0 = new ComplexEmployee("B", 1000); comp.addPresident(emp0);/*from ww w. ja va 2 s . c o m*/ ComplexDepartment sales = new ComplexDepartment("C"); ComplexEmployee emp1 = new ComplexEmployee("D", 1200); sales.addManager(emp1); comp.addDepartment(sales); ComplexDepartment accounting = new ComplexDepartment("E"); ComplexEmployee emp2 = new ComplexEmployee("F", 1230); accounting.addManager(emp2); comp.addDepartment(accounting); ComplexDepartment maintenance = new ComplexDepartment("Maintenance"); ComplexEmployee emp3 = new ComplexEmployee("Greg Hladlick", 1020); maintenance.addManager(emp3); comp.addDepartment(maintenance); oos.writeObject(comp); while ((str = (String) ois.readObject()) != null) { System.out.println(str); oos.writeObject("bye"); if (str.equals("bye")) break; } ois.close(); oos.close(); socket1.close(); }
From source file:GenericClient.java
public static void main(String[] args) throws IOException { try {// w w w. ja va 2s . co m // 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:Main.java
public static void main(String[] args) throws Exception { String serverName = args[0];/*from w ww . j a v a 2s . co m*/ int port = Integer.parseInt(args[1]); try { System.out.println("Connecting to " + serverName + " on port " + port); Socket client = new Socket(serverName, port); System.out.println("Just connected to " + client.getRemoteSocketAddress()); OutputStream outToServer = client.getOutputStream(); DataOutputStream out = new DataOutputStream(outToServer); out.writeUTF("Hello from " + client.getLocalSocketAddress()); InputStream inFromServer = client.getInputStream(); DataInputStream in = new DataInputStream(inFromServer); System.out.println("Server says " + in.readUTF()); client.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:whois.java
public static void main(String[] args) { Socket theSocket; DataInputStream theWhoisStream; PrintStream ps;// w w w .j ava 2 s. co m try { theSocket = new Socket(hostname, port, true); ps = new PrintStream(theSocket.getOutputStream()); for (int i = 0; i < args.length; i++) ps.print(args[i] + " "); ps.print("\r\n"); theWhoisStream = new DataInputStream(theSocket.getInputStream()); String s; while ((s = theWhoisStream.readLine()) != null) { System.out.println(s); } } catch (IOException e) { System.err.println(e); } }
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;/* ww w . ja va 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:com.couragelabs.logging.LogAppenderTestFixture.java
/** * Use this method to test the appender. Run this first, then run * GlobalContextSocketAppender::main/* w w w . jav 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..."); } }