List of usage examples for java.net Socket getInputStream
public InputStream getInputStream() throws IOException
From source file:br.com.i9torpedos.model.service.serverSocket.DSSocketSIM2.java
@Override public void run() { try {/* w ww. j a v a2s .co m*/ while (true) { Socket socket = server.accept(); log.info("Cliente conectado " + socket.getInetAddress()); try { PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true); printWriter.println(new Date().toString() + "Teste Servidor"); log.info("Sinal de autenticao enviado para o Cliente " + new Date().toString()); //Faz verificao no fluxo de entrada do Objeto ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream()); try { //faz a leitura do Objeto de entrada Object readObject = objectInputStream.readObject(); if (readObject instanceof SendSMSMessage) { try { SendSMSMessage smsMessage = (SendSMSMessage) readObject; // Thread.sleep(random.nextInt(10000)); ponte.set(smsMessage); new Thread(new ConsumerSendSMSMessage(ponte), "PONTE_ASYNC_DSSOCKETSIM2").start(); listaSMS.add(smsMessage); objectInputStream.close(); socket.close(); if (listaSMS.size() > 0 && !listaSMS.isEmpty()) { DServiceModem2 md2 = new DServiceModem2(listaSMS, 10000); new Thread(md2, "MODEM 2").start(); listaSMS.clear(); } } catch (InterruptedException ex) { Logger.getLogger(DSSocketSIM2.class.getName()).log(Level.SEVERE, null, ex); } } } catch (ClassNotFoundException ex) { Logger.getLogger(DSSocketSIM2.class.getName()).log(Level.SEVERE, null, ex); } } catch (IOException ex) { Logger.getLogger(DSSocketSIM2.class.getName()).log(Level.SEVERE, null, ex); } finally { try { socket.close(); } catch (IOException ex) { Logger.getLogger(DSSocketSIM2.class.getName()).log(Level.SEVERE, null, ex); } } } } catch (IOException ex) { Logger.getLogger(DSSocketSIM2.class.getName()).log(Level.SEVERE, null, ex); } finally { try { server.close(); } catch (IOException ex) { Logger.getLogger(DSSocketSIM2.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:net.lightbody.bmp.proxy.jetty.util.ThreadedServer.java
/** * Handle new connection. If access is required to the actual socket, override this method * instead of handleConnection(InputStream in,OutputStream out). The default implementation of * this just calls handleConnection(InputStream in,OutputStream out). *//* w w w.j ava2s . c o m*/ protected void handleConnection(Socket connection) throws IOException { if (log.isDebugEnabled()) log.debug("Handle " + connection); InputStream in = connection.getInputStream(); OutputStream out = connection.getOutputStream(); handleConnection(in, out); out.flush(); in = null; out = null; connection.close(); }
From source file:TalkServerThread.java
TalkServerThread(Socket socket, TalkServer server) throws IOException { super("TalkServer"); is = new BufferedReader( new InputStreamReader(socket.getInputStream())); os = new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())); if (is == null) { System.err.println("TalkServerThread: Input stream seemed " + "to be created successfully, but it's null."); throw new IOException(); }/* ww w . ja v a 2 s . com*/ if (os == null) { System.err.println("TalkServerThread: Output stream seemed " + "to be created successfully, but it's null."); throw new IOException(); } this.socket = socket; this.server = server; }
From source file:com.twinsoft.convertigo.eclipse.learnproxy.http.HttpProxyWorker.java
private HttpRequest handleRequest(Socket proxySocket) throws IOException { HttpRequest request = new HttpRequest(); BufferedInputStream proxyInStream = new BufferedInputStream(proxySocket.getInputStream()); byte b = -1;//from w w w . j ava 2 s .c om ArrayList<Byte> list = new ArrayList<Byte>(200); ArrayList<Byte> listToSend = new ArrayList<Byte>(200); int readInt; String previousLine = null; int lastCRPos = 0; int lastSendCRPos = 0; boolean hasCompleted = false; int lineNo = 0; int length = 0; while (!isInterrupted && !hasCompleted && (readInt = proxyInStream.read()) != -1) { b = (byte) readInt; list.add(new Byte(b)); listToSend.add(new Byte(b)); if (b == 13) { // check for two line breaks without form feed if (list.size() > 1) { if (list.get(list.size() - 2).equals(new Byte((byte) 13))) { hasCompleted = true; } else { // try to analyze the previous line byte[] bytes = new byte[list.size() - lastCRPos - 1]; for (int i = lastCRPos; i < list.size() - 1; i++) { bytes[i - lastCRPos] = ((Byte) list.get(i)).byteValue(); } // requests are always in ASCII previousLine = new String(bytes, "ISO-8859-1"); //logger.debug("request: " + previousLine); if (lineNo == 0) { // we must have here s.th. like // GET http://server/xyz.html?param=value HTTP/1.0 String[] components = previousLine.split(" "); String method = components[0]; String urlStr = components[1]; String httpVersion = components[2]; // now parse the URL URL url = new URL(urlStr); String host = url.getHost(); String path = url.getPath(); String query = url.getQuery(); String port = String.valueOf(url.getPort()); if ("-1".equals(port)) { port = "80"; } request.setPort(Integer.parseInt(port)); request.setHost(host); request.setPath(path); request.setQuery(query); request.setMethod(method); request.setVersion(httpVersion); // now we can reconstruct this line... if ((System.getProperty("http.proxyHost") == null) || System.getProperty("http.proxyHost").trim().equals("")) { listToSend = new ArrayList<Byte>(); StringBuffer buff = new StringBuffer(100); buff.append(method); buff.append(' '); buff.append(path); if (query != null) { buff.append('?'); buff.append(query); } buff.append(' '); buff.append(components[2].substring(0, components[2].length())); String newLine = buff.toString(); byte[] newLineBytes = newLine.getBytes("ISO-8859-1"); for (int i = 0; i < newLineBytes.length; i++) { listToSend.add(new Byte(newLineBytes[i])); } listToSend.add(new Byte((byte) 13)); } } if (previousLine.matches("^[Cc]ontent-[Ll]ength: .+")) { String lengthStr = previousLine.substring(16, previousLine.length()); length = Integer.parseInt(lengthStr); //logger.debug("length: " + length + ", " + lengthStr); } if (previousLine.matches("^[Pp]roxy.+")) { if ((System.getProperty("http.proxyHost") == null) || System.getProperty("http.proxyHost").trim().equals("")) { //logger.debug("proxy!!! - " + previousLine); // if not used behind another proxy erase proxy-related headers for (int i = listToSend.size() - 1; i > lastSendCRPos - 2; i--) { listToSend.remove(i); } } } // the CR should be ignored for printing any headerLine lastCRPos = list.size() + 1; lastSendCRPos = listToSend.size() + 1; lineNo++; } } } if (b == 10) { // check for two line breaks with form feed if (list.get(list.size() - 2).equals(new Byte((byte) 13)) && list.get(list.size() - 3).equals(new Byte((byte) 10)) && list.get(list.size() - 4).equals(new Byte((byte) 13))) { //logger.debug("length: " + length); if (length == 0) { hasCompleted = true; } else { for (int i = 0; i < length; i++) { readInt = proxyInStream.read(); b = (byte) readInt; list.add(new Byte(b)); listToSend.add(new Byte(b)); } list.add(new Byte((byte) '\n')); listToSend.add(new Byte((byte) '\n')); hasCompleted = true; } } } } // store original request byte[] byteArray = getByteArrayFromList(listToSend); request.setRequest(byteArray); //logger.debug("request: \nasText:\n" + new String(byteArray) + "as bytes:\n" + printByteArray(byteArray)); return request; }
From source file:org.dcache.srm.client.GsiConnectionSocketFactory.java
private void delegate(Socket socket, HttpClientTransport.Delegation delegation, X509Credential credential) throws IOException { if (delegation != null) { switch (delegation) { case SKIP: break; case NONE: socket.getOutputStream().write('0'); socket.getOutputStream().flush(); break; case LIMITED: case FULL: socket.getOutputStream().write('D'); socket.getOutputStream().flush(); try { // read csr ASN1InputStream dIn = new ASN1InputStream(socket.getInputStream()); PKCS10CertificationRequest csr = new PKCS10CertificationRequest( CertificationRequest.getInstance(dIn.readObject())); // generate proxy ProxyRequestOptions options = new ProxyRequestOptions(credential.getCertificateChain(), csr); options.setLimited(delegation == HttpClientTransport.Delegation.LIMITED); X509Certificate[] chain = ProxyGenerator.generate(options, credential.getKey()); // send to server socket.getOutputStream().write(chain[0].getEncoded()); socket.getOutputStream().flush(); } catch (SignatureException | NoSuchProviderException | CertificateEncodingException | InvalidKeyException | NoSuchAlgorithmException | CertificateParsingException e) { throw new IOException("Failed to signed CSR during delegation: " + e.getMessage(), e); }/*from w w w . j a va2 s . c om*/ break; } } }
From source file:ch.unifr.pai.twice.widgets.mpproxy.server.JettyProxy.java
public void handleConnect(HttpServletRequest request, HttpServletResponse response) throws IOException { String uri = request.getRequestURI(); String port = ""; String host = ""; int c = uri.indexOf(':'); if (c >= 0) { port = uri.substring(c + 1);// w w w.ja va 2s. c om host = uri.substring(0, c); if (host.indexOf('/') > 0) host = host.substring(host.indexOf('/') + 1); } InetSocketAddress inetAddress = new InetSocketAddress(host, Integer.parseInt(port)); // if // (isForbidden(HttpMessage.__SSL_SCHEME,addrPort.getHost(),addrPort.getPort(),false)) // { // sendForbid(request,response,uri); // } // else { InputStream in = request.getInputStream(); final OutputStream out = response.getOutputStream(); final Socket socket = new Socket(inetAddress.getAddress(), inetAddress.getPort()); response.setStatus(200); response.setHeader("Connection", "close"); response.flushBuffer(); // try { // Thread copy = new Thread(new Runnable() { // public void run() { // try { IOUtils.copy(socket.getInputStream(), out); // } catch (IOException e) { // e.printStackTrace(); // } // } // }); // copy.start(); IOUtils.copy(in, socket.getOutputStream()); // copy.join(); // copy.join(10000); // } // catch (InterruptedException e) { // e.printStackTrace(); // } } }
From source file:com.cyberway.issue.crawler.fetcher.FetchFTP.java
/** * Saves the given socket to the given recorder. * // www . j av a2s . c om * @param curi the curi that owns the recorder * @param socket the socket whose streams to save * @param recorder the recorder to save them to * @throws IOException if a network or file error occurs * @throws InterruptedException if the thread is interrupted */ private void saveToRecorder(CrawlURI curi, Socket socket, HttpRecorder recorder) throws IOException, InterruptedException { curi.setHttpRecorder(recorder); recorder.markContentBegin(); recorder.inputWrap(socket.getInputStream()); recorder.outputWrap(socket.getOutputStream()); // Read the remote file/dir listing in its entirety. long softMax = 0; long hardMax = getMaxLength(curi); long timeout = (long) getTimeout(curi) * 1000; int maxRate = getFetchBandwidth(curi); RecordingInputStream input = recorder.getRecordedInput(); input.setLimits(hardMax, timeout, maxRate); input.readFullyOrUntil(softMax); }
From source file:com.supernovapps.audio.jstreamsourcer.Icecast.java
public boolean start(Socket sock) { try {/*from www . j a va2 s .co m*/ this.sock = sock; sock.connect(new InetSocketAddress(host, port), timeout); sock.setSendBufferSize(64 * 1024); out = sock.getOutputStream(); PrintWriter output = new PrintWriter(out); output.println("SOURCE " + path + " HTTP/1.0"); writeAuthentication(output); writeHeaders(output); output.println(""); output.flush(); InputStreamReader isr = new InputStreamReader(sock.getInputStream()); BufferedReader in = new BufferedReader(isr); String line = in.readLine(); if (line == null || !line.contains("HTTP") || !line.contains("OK")) { if (listener != null) { listener.onError("Connection / Authentification error"); } return false; } } catch (Exception e) { e.printStackTrace(); try { if (sock != null) { sock.close(); } } catch (IOException e1) { e1.printStackTrace(); } if (listener != null) { listener.onError("Connection / Authentification error"); } return false; } started = true; if (listener != null) { listener.onConnected(); } return true; }
From source file:com.bmwcarit.barefoot.tracker.TrackerServerTest.java
public void sendSample(InetAddress host, int port, JSONObject sample) throws InterruptedException, IOException { int trials = 120; int timeout = 500; Socket client = null; while (client == null || !client.isConnected()) { try {/*w ww . j av a 2 s .c o m*/ client = new Socket(host, port); } catch (IOException e) { Thread.sleep(timeout); if (trials == 0) { logger.error(e.getMessage()); client.close(); throw new IOException(); } else { trials -= 1; } } } PrintWriter writer = new PrintWriter(client.getOutputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream())); writer.println(sample.toString()); writer.flush(); String code = reader.readLine(); assertEquals("SUCCESS", code); }
From source file:com.jredrain.startup.Bootstrap.java
private void await() throws Exception { // Negative values - don't wait on port - redrain is embedded or we just don't like ports if (port == -2) { return;/*from w ww . jav a2s.c o m*/ } if (port == -1) { try { awaitThread = Thread.currentThread(); while (!stopAwait) { try { Thread.sleep(10000); } catch (InterruptedException ex) { // continue and check the flag } } } finally { awaitThread = null; } return; } // Set up a server socket to wait on try { awaitSocket = new ServerSocket(RedrainProperties.getInt("redrain.shutdown")); } catch (IOException e) { logger.error("[redrain] agent .await: create[{}] ", RedrainProperties.getInt("redrain.shutdown"), e); return; } try { awaitThread = Thread.currentThread(); // Loop waiting for a connection and a valid command while (!stopAwait) { ServerSocket serverSocket = awaitSocket; if (serverSocket == null) { break; } // Wait for the next connection Socket socket = null; StringBuilder command = new StringBuilder(); try { InputStream stream; long acceptStartTime = System.currentTimeMillis(); try { socket = serverSocket.accept(); socket.setSoTimeout(10 * 1000); // Ten seconds stream = socket.getInputStream(); } catch (SocketTimeoutException ste) { // This should never happen but bug 56684 suggests that // it does. logger.warn("[redrain] agentServer accept.timeout", Long.valueOf(System.currentTimeMillis() - acceptStartTime), ste); continue; } catch (AccessControlException ace) { logger.warn("[redrain] agentServer .accept security exception: {}", ace.getMessage(), ace); continue; } catch (IOException e) { if (stopAwait) { break; } logger.error("[redrain] agent .await: accept: ", e); break; } // Read a set of characters from the socket int expected = 1024; // Cut off to avoid DoS attack while (expected < shutdown.length()) { if (random == null) { random = new Random(); } expected += (random.nextInt() % 1024); } while (expected > 0) { int ch = -1; try { ch = stream.read(); } catch (IOException e) { logger.warn("[redrain] agent .await: read: ", e); ch = -1; } if (ch < 32) // Control character or EOF terminates loop break; command.append((char) ch); expected--; } } finally { try { if (socket != null) { socket.close(); } } catch (IOException e) { } } boolean match = command.toString().equals(shutdown); if (match) { break; } else { logger.warn("[redrain] agent .await: Invalid command '" + command.toString() + "' received"); } } } finally { ServerSocket serverSocket = awaitSocket; awaitThread = null; awaitSocket = null; // Close the server socket and return if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { // Ignore } } } }