List of usage examples for java.net Socket getInputStream
public InputStream getInputStream() throws IOException
From source file:com.kab.channel66.StreamProxy.java
private HttpRequest readRequest(Socket client) { HttpRequest request = null;//from w w w.j a v a 2 s . c o m InputStream is; String firstLine; try { is = client.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); firstLine = reader.readLine(); } catch (IOException e) { Log.e(LOG_TAG, "Error parsing request", e); return request; } if (firstLine == null) { Log.i(LOG_TAG, "Proxy client closed connection without a request."); return request; } StringTokenizer st = new StringTokenizer(firstLine); String method = st.nextToken(); String uri = st.nextToken(); Log.d(LOG_TAG, uri); String realUri = uri.substring(1); Log.d(LOG_TAG, realUri); request = new BasicHttpRequest(method, realUri); return request; }
From source file:edu.umass.cs.msocket.common.policies.GeoLoadProxyPolicy.java
/** * @throws Exception if a GNS error occurs * @see edu.umass.cs.msocket.common.policies.ProxySelectionPolicy#getNewProxy() *//* ww w . jav a 2 s . c om*/ @Override public List<InetSocketAddress> getNewProxy() throws Exception { // Lookup for active location service GUIDs final UniversalGnsClient gnsClient = gnsCredentials.getGnsClient(); final GuidEntry guidEntry = gnsCredentials.getGuidEntry(); JSONArray guids; try { guids = gnsClient.fieldRead(proxyGroupName, GnsConstants.ACTIVE_LOCATION_FIELD, guidEntry); } catch (Exception e) { throw new GnsException("Could not find active location services (" + e + ")"); } // Try every location proxy in the list until one works for (int i = 0; i < guids.length(); i++) { // Retrieve the location service IP and connect to it String locationGuid = guids.getString(i); String locationIP = gnsClient.fieldRead(locationGuid, GnsConstants.LOCATION_SERVICE_IP, guidEntry) .getString(0); logger.fine("Contacting location service " + locationIP + " to request " + numProxies + " proxies"); // Location IP is stored as host:port StringTokenizer st = new StringTokenizer(locationIP, ":"); try { // Protocol is send the number of desired proxies and receive strings // containing proxy IP:port Socket s = new Socket(st.nextToken(), Integer.parseInt(st.nextToken())); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); ObjectInputStream ois = new ObjectInputStream(s.getInputStream()); oos.writeInt(numProxies); oos.flush(); List<InetSocketAddress> result = new LinkedList<InetSocketAddress>(); while (!s.isClosed() && result.size() < numProxies) { String proxyIP = ois.readUTF(); StringTokenizer stp = new StringTokenizer(proxyIP, ":"); result.add(new InetSocketAddress(stp.nextToken(), Integer.parseInt(stp.nextToken()))); } if (!s.isClosed()) // We receive all the proxies we need, just close the // socket s.close(); return result; } catch (Exception e) { logger.info("Failed to obtain proxy from location service" + locationIP + " (" + e + ")"); } } throw new GnsException("Could not find any location service to provide a geolocated proxy"); }
From source file:client.gui.ConnectionDialog.java
public void actionPerformed(final ActionEvent event) { String nick = null;//from w w w.j a v a 2s.c om String host = null; int port = 0; if (event.getSource() == connect) { nick = this.nick.getText(); host = this.host.getText(); try { port = Integer.parseInt(this.port.getText()); } catch (NumberFormatException e1) { new MyDialog("Port number must be integer").setVisible(true); return; } } else if (event.getSource() == connectDev) { nick = generateNick(); host = "localhost"; port = 5555; } else if (event.getSource() == connectSame) { nick = "a"; host = "localhost"; port = 5555; } if (port <= 0) { new MyDialog("Port number must be bigger than 0").setVisible(true); return; } Socket socket; BufferedReader in; try { socket = new Socket(host, port); GlobalVariables.out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (java.net.UnknownHostException e2) { new MyDialog("Unknown host").setVisible(true); return; } catch (IOException e3) { new MyDialog("Connection unsuccessful").setVisible(true); GlobalVariables.connected = false; return; } catch (java.lang.IllegalArgumentException e4) { new MyDialog("Port number is too big").setVisible(true); return; } System.out.println("Nick: " + nick); final JSONArray toSend = new JSONArray(); try { toSend.put(new JSONObject().put("action", "first_connection")); toSend.put(new JSONObject().put("nick", nick)); } catch (JSONException e1) { e1.printStackTrace(); } GlobalVariables.daemon = true; GlobalVariables.me.setNick(nick); GlobalVariables.connect.setEnabled(false); GlobalVariables.connected = true; setVisible(false); GlobalVariables.out.println(toSend); Thread thread; thread = new ReceivingData(in); thread.setDaemon(true); thread.start(); }
From source file:com.myapplication.ServerService.java
@Override protected void onHandleIntent(Intent intent) { ServerSocket serverSocket;/*ww w .j av a2 s. co m*/ Socket socket; try { serverSocket = new ServerSocket(Constant.SERVER_PORT); while (true) { //Listen for incoming connections on specified port //Block thread until someone connects socket = serverSocket.accept(); clientAddress = socket.getInetAddress().getHostAddress(); InputStream is = socket.getInputStream(); String receivedMessage = CommonUtils.getStringFromInputStream(is); CommonUtils.showToast(receivedMessage); Intent messageIntent = new Intent(Constant.ACTION_MESSAGE_FROM_PEER); messageIntent.putExtra(Constant.KEY_MESSAGE_FROM_PEER, receivedMessage); LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(messageIntent); socket.close(); } } catch (Exception e) { CommonUtils.showToast(e.getMessage()); } }
From source file:com.chigix.bio.proxy.buffer.FixedBufferTest.java
License:asdf
@Test public void testGoogleConnect() { System.out.println("BANKAI"); Socket tmp_socket = null;//from ww w .ja va 2 s .c o m try { tmp_socket = new Socket("www.google.com", 80); } catch (IOException ex) { Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex); } final Socket socket = tmp_socket; new Thread() { @Override public void run() { while (true) { try { int read; System.out.print(read = socket.getInputStream().read()); System.out.print("[" + (char) read + "]"); System.out.print(","); } catch (IOException ex) { Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex); } } } }.start(); try { //socket.getOutputStream().write("GET http://www.google.com/ HTTP/1.0\r\nHost: www.google.com\r\nConnection: close\r\n\n".getBytes()); //URI uri = new URI("/?gfe_rd=cr&ei=F07YVIjKBe_98wfq74LICw"); URI uri = new URI("/asdfwef?"); System.out.println(uri.getRawFragment()); System.out.println(uri.getRawPath()); System.out.println(uri.getRawQuery()); System.out.println(uri.getRawSchemeSpecificPart()); socket.getOutputStream() .write(("GET / HTTP/1.0\r\nHost: www.google.com\r\nConnection: close\r\n\r\n").getBytes()); System.out.println("REQUEST SENT"); } catch (IOException ex) { Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex); } catch (URISyntaxException ex) { Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex); } try { Thread.sleep(50000); } catch (InterruptedException ex) { Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:jetbrains.exodus.util.ForkSupportIO.java
@NotNull private Process spawnProcess() throws IOException { final Process process = builder.start(); log.info("Waiting for connection..."); final Socket connection = serverSocket.accept(); log.info("Connection received from " + connection.getInetAddress().getHostName()); log.info("Waiting to receive process Id"); streamer = new Streamer(connection.getInputStream(), connection.getOutputStream()); String idString = streamer.readString(); processId = Integer.parseInt(idString); return process; }
From source file:com.mendhak.gpslogger.common.network.CertificateValidationWorkflow.java
@Override public void run() { try {/*from w w w . ja v a 2s . co m*/ LOG.debug("Beginning certificate validation - will connect directly to {} port {}", host, String.valueOf(port)); try { LOG.debug("Trying handshake first in case the socket is SSL/TLS only"); connectToSSLSocket(null); postValidationHandler.post(new Runnable() { @Override public void run() { onWorkflowFinished(context, null, true); } }); } catch (final Exception e) { if (Networks.extractCertificateValidationException(e) != null) { throw e; } LOG.debug("Direct connection failed or no certificate was presented", e); if (serverType == ServerType.HTTPS) { postValidationHandler.post(new Runnable() { @Override public void run() { onWorkflowFinished(context, e, false); } }); return; } LOG.debug("Now attempting to connect over plain socket"); Socket plainSocket = new Socket(host, port); plainSocket.setSoTimeout(30000); BufferedReader reader = new BufferedReader(new InputStreamReader(plainSocket.getInputStream())); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(plainSocket.getOutputStream())); String line; if (serverType == ServerType.SMTP) { LOG.debug("CLIENT: EHLO localhost"); writer.write("EHLO localhost\r\n"); writer.flush(); line = reader.readLine(); LOG.debug("SERVER: " + line); } String command = "", regexToMatch = ""; if (serverType == ServerType.FTP) { LOG.debug("FTP type server"); command = "AUTH SSL\r\n"; regexToMatch = "(?:234.*)"; } else if (serverType == ServerType.SMTP) { LOG.debug("SMTP type server"); command = "STARTTLS\r\n"; regexToMatch = "(?i:220 .* Ready.*)"; } LOG.debug("CLIENT: " + command); LOG.debug("(Expecting regex {} in response)", regexToMatch); writer.write(command); writer.flush(); while ((line = reader.readLine()) != null) { LOG.debug("SERVER: " + line); if (line.matches(regexToMatch)) { LOG.debug("Elevating socket and attempting handshake"); connectToSSLSocket(plainSocket); postValidationHandler.post(new Runnable() { @Override public void run() { onWorkflowFinished(context, null, true); } }); return; } } LOG.debug("No certificates found. Giving up."); postValidationHandler.post(new Runnable() { @Override public void run() { onWorkflowFinished(context, null, false); } }); } } catch (final Exception e) { LOG.debug("", e); postValidationHandler.post(new Runnable() { @Override public void run() { onWorkflowFinished(context, e, false); } }); } }
From source file:com.techcavern.pircbotz.IdentServer.java
/** * Waits for a client to connect to the ident server before making an * appropriate response./*from w w w . j a v a 2s . c om*/ */ public void run() { log.info("IdentServer running on port " + serverSocket.getLocalPort()); //TODO: Multi-thread this while (!serverSocket.isClosed()) { Socket socket = null; try { socket = serverSocket.accept(); BufferedReader reader = new BufferedReader( new InputStreamReader(socket.getInputStream(), encoding)); OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream(), encoding); InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress(); //Read first line and process String line = reader.readLine(); String response = handleNextConnection(remoteAddress, line); if (response != null) { writer.write(response); writer.flush(); } } catch (Exception e) { if (serverSocket.isClosed()) { log.debug("Server socket closed, exiting connection loop"); return; } else //This is not from the server socket closing throw new RuntimeException("Exception encountered when opening user socket"); } finally { //Close user socket try { if (socket != null) socket.close(); } catch (IOException e) { throw new RuntimeException("Exception encountered when closing user socket"); } } } //Done with connection loop, can safely close the socket now if (!serverSocket.isClosed()) try { close(); } catch (IOException e) { log.error("Cannot close IdentServer socket", e); } }
From source file:org.apache.flink.streaming.api.functions.sink.SocketClientSinkTest.java
@Test public void testRetry() throws Exception { final ServerSocket[] serverSocket = new ServerSocket[1]; final ExecutorService[] executor = new ExecutorService[1]; try {//w w w . jav a 2s . c o m serverSocket[0] = new ServerSocket(0); executor[0] = Executors.newCachedThreadPool(); int port = serverSocket[0].getLocalPort(); Callable<Void> serverTask = new Callable<Void>() { @Override public Void call() throws Exception { Socket socket = serverSocket[0].accept(); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); String value = reader.readLine(); assertEquals("0", value); socket.close(); return null; } }; Future<Void> serverFuture = executor[0].submit(serverTask); final SocketClientSink<String> sink = new SocketClientSink<>(host, serverSocket[0].getLocalPort(), simpleSchema, -1, true); // Create the connection sink.open(new Configuration()); // Initial payload => this will be received by the server an then the socket will be // closed. sink.invoke("0\n"); // Get future an make sure there was no problem. This will rethrow any Exceptions from // the server. serverFuture.get(); // Shutdown the server socket serverSocket[0].close(); assertTrue(serverSocket[0].isClosed()); // No retries expected at this point assertEquals(0, sink.getCurrentNumberOfRetries()); final CountDownLatch retryLatch = new CountDownLatch(1); final CountDownLatch again = new CountDownLatch(1); Callable<Void> sinkTask = new Callable<Void>() { @Override public Void call() throws Exception { // Send next payload => server is down, should try to reconnect. // We need to send more than just one packet to notice the closed connection. while (retryLatch.getCount() != 0) { sink.invoke("1\n"); } return null; } }; Future<Void> sinkFuture = executor[0].submit(sinkTask); while (sink.getCurrentNumberOfRetries() == 0) { // Wait for a retry Thread.sleep(100); } // OK the poor guy retried to write retryLatch.countDown(); // Restart the server serverSocket[0] = new ServerSocket(port); Socket socket = serverSocket[0].accept(); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // Wait for the reconnect String value = reader.readLine(); assertEquals("1", value); // OK the sink re-connected. :) } finally { if (serverSocket[0] != null) { serverSocket[0].close(); } if (executor[0] != null) { executor[0].shutdown(); } } }
From source file:net.arccotangent.pacchat.net.KeyUpdateClient.java
public void run() { Socket socket; BufferedReader input;/*from w w w. j ava 2 s . co m*/ BufferedWriter output; kuc_log.i("Connecting to server at " + server_ip); try { socket = new Socket(); socket.connect(new InetSocketAddress(InetAddress.getByName(server_ip), Server.PORT), 1000); input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); } catch (SocketTimeoutException e) { kuc_log.e("Connection to server timed out!"); e.printStackTrace(); return; } catch (ConnectException e) { kuc_log.e("Connection to server was refused!"); e.printStackTrace(); return; } catch (UnknownHostException e) { kuc_log.e("You entered an invalid IP address!"); e.printStackTrace(); return; } catch (IOException e) { kuc_log.e("Error connecting to server!"); e.printStackTrace(); return; } try { kuc_log.i("Requesting a key update."); output.write("302 request key update"); output.newLine(); output.flush(); kuc_log.i("Awaiting response from server."); String update = input.readLine(); switch (update) { case "303 update": kuc_log.i("Server accepted update request, sending public key."); String pubkeyB64 = Base64.encodeBase64String(Main.getKeypair().getPublic().getEncoded()); output.write(pubkeyB64); output.newLine(); output.flush(); output.close(); break; case "304 no update": kuc_log.i("Server rejected update request, closing connection."); input.close(); output.close(); break; case "305 update unavailable": kuc_log.i("Server cannot update at this time, try again later."); input.close(); output.close(); break; default: kuc_log.i("Server sent back invalid response"); input.close(); output.close(); break; } } catch (IOException e) { kuc_log.e("Error in key update request!"); e.printStackTrace(); } }