List of usage examples for java.net Socket getInputStream
public InputStream getInputStream() throws IOException
From source file:net.lightbody.bmp.proxy.jetty.http.handler.ProxyHandler.java
protected HttpTunnel newHttpTunnel(HttpRequest request, HttpResponse response, InetAddress iaddr, int port, int timeoutMS) throws IOException { try {//from ww w . jav a 2 s.com Socket socket = null; InputStream in = null; String chained_proxy_host = System.getProperty("http.proxyHost"); if (chained_proxy_host == null) { socket = new Socket(iaddr, port); socket.setSoTimeout(timeoutMS); socket.setTcpNoDelay(true); } else { int chained_proxy_port = Integer.getInteger("http.proxyPort", 8888).intValue(); Socket chain_socket = new Socket(chained_proxy_host, chained_proxy_port); chain_socket.setSoTimeout(timeoutMS); chain_socket.setTcpNoDelay(true); if (log.isDebugEnabled()) log.debug("chain proxy socket=" + chain_socket); LineInput line_in = new LineInput(chain_socket.getInputStream()); byte[] connect = request.toString() .getBytes(net.lightbody.bmp.proxy.jetty.util.StringUtil.__ISO_8859_1); chain_socket.getOutputStream().write(connect); String chain_response_line = line_in.readLine(); HttpFields chain_response = new HttpFields(); chain_response.read(line_in); // decode response int space0 = chain_response_line.indexOf(' '); if (space0 > 0 && space0 + 1 < chain_response_line.length()) { int space1 = chain_response_line.indexOf(' ', space0 + 1); if (space1 > space0) { int code = Integer.parseInt(chain_response_line.substring(space0 + 1, space1)); if (code >= 200 && code < 300) { socket = chain_socket; in = line_in; } else { Enumeration iter = chain_response.getFieldNames(); while (iter.hasMoreElements()) { String name = (String) iter.nextElement(); if (!_DontProxyHeaders.containsKey(name)) { Enumeration values = chain_response.getValues(name); while (values.hasMoreElements()) { String value = (String) values.nextElement(); response.setField(name, value); } } } response.sendError(code); if (!chain_socket.isClosed()) chain_socket.close(); } } } } if (socket == null) return null; HttpTunnel tunnel = new HttpTunnel(socket, in, null); return tunnel; } catch (IOException e) { log.debug(e); response.sendError(HttpResponse.__400_Bad_Request); return null; } }
From source file:com.plotsquared.iserver.core.Worker.java
/** * Prepares a request, then calls {@link #handle} * @param remote Client socket/*from w w w. ja va 2 s . c om*/ */ private void handle(final Socket remote) { // Used for metrics final Timer.Context timerContext = Server.getInstance().getMetrics().registerRequestHandling(); if (CoreConfig.verbose) { // Do we want to output a load of useless information? server.log(Message.CONNECTION_ACCEPTED, remote.getInetAddress()); } final BufferedReader input; { // Read the actual request try { input = new BufferedReader(new InputStreamReader(remote.getInputStream()), CoreConfig.Buffer.in); output = new BufferedOutputStream(remote.getOutputStream(), CoreConfig.Buffer.out); final List<String> lines = new ArrayList<>(); String str; while ((str = input.readLine()) != null && !str.isEmpty()) { lines.add(str); } request = new Request(lines, remote); if (request.getQuery().getMethod() == HttpMethod.POST) { final int cl = Integer.parseInt(request.getHeader("Content-Length").substring(1)); request.setPostRequest(PostRequest.construct(request, cl, input)); } } catch (final Exception e) { e.printStackTrace(); return; } } if (!server.silent) { server.log(request.buildLog()); } handle(); timerContext.stop(); }
From source file:info.sugoiapps.xoserver.XOverServer.java
/** * The main background task./* w w w.j a v a 2 s . c o m*/ * Accept connection from the server socket and read incoming messages. * Pass messages to mouse event handler. */ private void listen() { Socket socket = null; InputStream in = null; publish(CONNECTED_MESSAGE + PORT); System.out.println("about to enter server loop"); while (!Thread.interrupted()) { //!Thread.interrupted() try { socket = server.accept(); // stop is clicked, this is still waiting for incoming connections, // therefore once the server is closed, it will produce an error //socket.setKeepAlive(false); System.out.println("started accepting from socket"); } catch (IOException ex) { serverClosedMessage(ex); break; } try { in = socket.getInputStream(); InputStreamReader isr = new InputStreamReader(in); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { if (isCancelled()) { in.close(); isr.close(); br.close(); socket.close(); break; } if (!addressReceived && isValidAddress(line)) { System.out.println("address check entered"); addressReceived = true; hostAddress = line; startFileClient(); } else { imitateMouse(line); } } } catch (IOException ex) { ex.printStackTrace(); serverClosedMessage(ex); } } }
From source file:com.clavain.munin.MuninNode.java
private void updateEssentials(Socket p_socket) { String decodestr = ""; try {/*from w ww .j a v a 2 s . com*/ PrintStream os = new PrintStream(p_socket.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(p_socket.getInputStream())); os.println("config muninmx_essentials"); // skip first line if starts with # decodestr = in.readLine(); if (decodestr.startsWith("#")) { decodestr = in.readLine(); } if (decodestr.equals(".")) { decodestr = in.readLine(); } BasicDBObject doc = new BasicDBObject(); doc.put("data", decodestr); doc.put("time", getUnixtime()); doc.put("node", this.node_id); doc.put("type", "essential"); com.clavain.muninmxcd.mongo_essential_queue.add(doc); logger.info("Essentials Updated for Node: " + this.getHostname() + ": received base64 (length): " + decodestr.length()); last_essentials_update = getUnixtime(); // read following . in.readLine(); } catch (Exception ex) { logger.error( "Error in updateEssentials for Node " + this.getHostname() + " : " + ex.getLocalizedMessage()); logger.error("updateEssentials for Node " + this.getHostname() + " received: " + decodestr); ex.printStackTrace(); } }
From source file:com.dumbster.smtp.SimpleSmtpServer.java
/** * Main loop of the SMTP server./*from w w w . j a va2 s . com*/ */ public void run() { stopped = false; try { try { serverSocket = new ServerSocket(port); serverSocket.setSoTimeout(TIMEOUT); // Block for maximum of 1.5 // seconds } finally { synchronized (this) { // Notify when server socket has been created notifyAll(); } } // Server: loop until stopped while (!isStopped()) { // Start server socket and listen for client connections Socket socket = null; try { socket = serverSocket.accept(); } catch (Exception e) { if (socket != null) { socket.close(); } continue; // Non-blocking socket timeout occurred: try // accept() again } // Get the input and output streams BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream()); synchronized (this) { /* * We synchronize over the handle method and the list update * because the client call completes inside the handle * method and we have to prevent the client from reading the * list until we've updated it. For higher concurrency, we * could just change handle to return void and update the * list inside the method to limit the duration that we hold * the lock. */ List<SmtpMessage> msgs = handleTransaction(out, input); saveMessagesInElasticSearch(msgs); } socket.close(); } } catch (Exception e) { logger.error("Smtp Server could not be started", e); } finally { if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:com.connectsdk.service.netcast.NetcastHttpServer.java
public void start() { //TODO: this method is too complex and should be refactored if (running)//from w w w . j av a2 s. com return; running = true; try { welcomeSocket = new ServerSocket(this.port); } catch (IOException ex) { ex.printStackTrace(); } while (running) { if (welcomeSocket == null || welcomeSocket.isClosed()) { stop(); break; } Socket connectionSocket = null; BufferedReader inFromClient = null; DataOutputStream outToClient = null; try { connectionSocket = welcomeSocket.accept(); } catch (IOException ex) { ex.printStackTrace(); // this socket may have been closed, so we'll stop stop(); return; } String str = null; int c; StringBuilder sb = new StringBuilder(); try { inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); while ((str = inFromClient.readLine()) != null) { if (str.equals("")) { break; } } while ((c = inFromClient.read()) != -1) { sb.append((char) c); String temp = sb.toString(); if (temp.endsWith("</envelope>")) break; } } catch (IOException ex) { ex.printStackTrace(); } String body = sb.toString(); Log.d(Util.T, "got message body: " + body); Calendar calendar = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); String date = dateFormat.format(calendar.getTime()); String androidOSVersion = android.os.Build.VERSION.RELEASE; PrintWriter out = null; try { outToClient = new DataOutputStream(connectionSocket.getOutputStream()); out = new PrintWriter(outToClient); out.println("HTTP/1.1 200 OK"); out.println("Server: Android/" + androidOSVersion + " UDAP/2.0 ConnectSDK/1.2.1"); out.println("Cache-Control: no-store, no-cache, must-revalidate"); out.println("Date: " + date); out.println("Connection: Close"); out.println("Content-Length: 0"); out.println(); out.flush(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { inFromClient.close(); out.close(); outToClient.close(); connectionSocket.close(); } catch (IOException ex) { ex.printStackTrace(); } } SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); InputStream stream = null; try { stream = new ByteArrayInputStream(body.getBytes("UTF-8")); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } NetcastPOSTRequestParser handler = new NetcastPOSTRequestParser(); SAXParser saxParser; try { saxParser = saxParserFactory.newSAXParser(); saxParser.parse(stream, handler); } catch (IOException ex) { ex.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } if (body.contains("ChannelChanged")) { ChannelInfo channel = NetcastChannelParser.parseRawChannelData(handler.getJSONObject()); Log.d(Util.T, "Channel Changed: " + channel.getNumber()); for (URLServiceSubscription<?> sub : subscriptions) { if (sub.getTarget().equalsIgnoreCase("ChannelChanged")) { for (int i = 0; i < sub.getListeners().size(); i++) { @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners() .get(i); Util.postSuccess(listener, channel); } } } } else if (body.contains("KeyboardVisible")) { boolean focused = false; TextInputStatusInfo keyboard = new TextInputStatusInfo(); keyboard.setRawData(handler.getJSONObject()); try { JSONObject currentWidget = (JSONObject) handler.getJSONObject().get("currentWidget"); focused = (Boolean) currentWidget.get("focus"); keyboard.setFocused(focused); } catch (JSONException e) { e.printStackTrace(); } Log.d(Util.T, "KeyboardFocused?: " + focused); for (URLServiceSubscription<?> sub : subscriptions) { if (sub.getTarget().equalsIgnoreCase("KeyboardVisible")) { for (int i = 0; i < sub.getListeners().size(); i++) { @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners() .get(i); Util.postSuccess(listener, keyboard); } } } } else if (body.contains("TextEdited")) { System.out.println("TextEdited"); String newValue = ""; try { newValue = handler.getJSONObject().getString("value"); } catch (JSONException ex) { ex.printStackTrace(); } Util.postSuccess(textChangedListener, newValue); } else if (body.contains("3DMode")) { try { String enabled = (String) handler.getJSONObject().get("value"); boolean bEnabled; bEnabled = enabled.equalsIgnoreCase("true"); for (URLServiceSubscription<?> sub : subscriptions) { if (sub.getTarget().equalsIgnoreCase("3DMode")) { for (int i = 0; i < sub.getListeners().size(); i++) { @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners() .get(i); Util.postSuccess(listener, bEnabled); } } } } catch (JSONException e) { e.printStackTrace(); } } } }
From source file:com.connectsdk.device.netcast.NetcastHttpServer.java
public void start() { if (running)//from w w w.ja v a 2s. c o m return; running = true; try { welcomeSocket = new ServerSocket(this.port); } catch (IOException ex) { ex.printStackTrace(); } while (running) { if (welcomeSocket == null || welcomeSocket.isClosed()) { stop(); break; } Socket connectionSocket = null; BufferedReader inFromClient = null; DataOutputStream outToClient = null; try { connectionSocket = welcomeSocket.accept(); } catch (IOException ex) { ex.printStackTrace(); // this socket may have been closed, so we'll stop stop(); return; } String str = null; int c; StringBuilder sb = new StringBuilder(); try { inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); while ((str = inFromClient.readLine()) != null) { if (str.equals("")) { break; } } while ((c = inFromClient.read()) != -1) { sb.append((char) c); String temp = sb.toString(); if (temp.endsWith("</envelope>")) break; } } catch (IOException ex) { ex.printStackTrace(); } String body = sb.toString(); Log.d("Connect SDK", "got message body: " + body); Calendar calendar = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); String date = dateFormat.format(calendar.getTime()); String androidOSVersion = android.os.Build.VERSION.RELEASE; PrintWriter out = null; try { outToClient = new DataOutputStream(connectionSocket.getOutputStream()); out = new PrintWriter(outToClient); out.println("HTTP/1.1 200 OK"); out.println("Server: Android/" + androidOSVersion + " UDAP/2.0 ConnectSDK/1.2.1"); out.println("Cache-Control: no-store, no-cache, must-revalidate"); out.println("Date: " + date); out.println("Connection: Close"); out.println("Content-Length: 0"); out.flush(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { inFromClient.close(); out.close(); outToClient.close(); connectionSocket.close(); } catch (IOException ex) { ex.printStackTrace(); } } SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); InputStream stream = null; try { stream = new ByteArrayInputStream(body.getBytes("UTF-8")); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } NetcastPOSTRequestParser handler = new NetcastPOSTRequestParser(); SAXParser saxParser; try { saxParser = saxParserFactory.newSAXParser(); saxParser.parse(stream, handler); } catch (IOException ex) { ex.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } if (body.contains("ChannelChanged")) { ChannelInfo channel = NetcastChannelParser.parseRawChannelData(handler.getJSONObject()); Log.d("Connect SDK", "Channel Changed: " + channel.getNumber()); for (URLServiceSubscription<?> sub : subscriptions) { if (sub.getTarget().equalsIgnoreCase("ChannelChanged")) { for (int i = 0; i < sub.getListeners().size(); i++) { @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners() .get(i); Util.postSuccess(listener, channel); } } } } else if (body.contains("KeyboardVisible")) { boolean focused = false; TextInputStatusInfo keyboard = new TextInputStatusInfo(); keyboard.setRawData(handler.getJSONObject()); try { JSONObject currentWidget = (JSONObject) handler.getJSONObject().get("currentWidget"); focused = (Boolean) currentWidget.get("focus"); keyboard.setFocused(focused); } catch (JSONException e) { e.printStackTrace(); } Log.d("Connect SDK", "KeyboardFocused?: " + focused); for (URLServiceSubscription<?> sub : subscriptions) { if (sub.getTarget().equalsIgnoreCase("KeyboardVisible")) { for (int i = 0; i < sub.getListeners().size(); i++) { @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners() .get(i); Util.postSuccess(listener, keyboard); } } } } else if (body.contains("TextEdited")) { System.out.println("TextEdited"); String newValue = ""; try { newValue = handler.getJSONObject().getString("value"); } catch (JSONException ex) { ex.printStackTrace(); } Util.postSuccess(textChangedListener, newValue); } else if (body.contains("3DMode")) { try { String enabled = (String) handler.getJSONObject().get("value"); boolean bEnabled; if (enabled.equalsIgnoreCase("true")) bEnabled = true; else bEnabled = false; for (URLServiceSubscription<?> sub : subscriptions) { if (sub.getTarget().equalsIgnoreCase("3DMode")) { for (int i = 0; i < sub.getListeners().size(); i++) { @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners() .get(i); Util.postSuccess(listener, bEnabled); } } } } catch (JSONException e) { e.printStackTrace(); } } } }
From source file:com.alexkli.jhb.Worker.java
@Override public void run() { try {/*from w ww .j a v a 2 s.c om*/ while (true) { long start = System.nanoTime(); QueueItem<HttpRequestBase> item = queue.take(); idleAvg.add(System.nanoTime() - start); if (item.isPoisonPill()) { return; } HttpRequestBase request = item.getRequest(); if ("java".equals(config.client)) { System.setProperty("http.keepAlive", "false"); item.sent(); try { HttpURLConnection http = (HttpURLConnection) new URL(request.getURI().toString()) .openConnection(); http.setConnectTimeout(5000); http.setReadTimeout(5000); int statusCode = http.getResponseCode(); consumeAndCloseStream(http.getInputStream()); if (statusCode == 200) { item.done(); } else { item.failed(); } } catch (IOException e) { System.err.println("Failed request: " + e.getMessage()); e.printStackTrace(); // System.exit(2); item.failed(); } } else if ("ahc".equals(config.client)) { try { item.sent(); try (CloseableHttpResponse response = httpClient.execute(request, context)) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { item.done(); } else { item.failed(); } } } catch (IOException e) { System.err.println("Failed request: " + e.getMessage()); item.failed(); } } else if ("fast".equals(config.client)) { try { URI uri = request.getURI(); item.sent(); InetAddress addr = InetAddress.getByName(uri.getHost()); Socket socket = new Socket(addr, uri.getPort()); PrintWriter out = new PrintWriter(socket.getOutputStream()); // BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); // send an HTTP request to the web server out.println("GET / HTTP/1.1"); out.append("Host: ").append(uri.getHost()).append(":").println(uri.getPort()); out.println("Connection: Close"); out.println(); out.flush(); // read the response consumeAndCloseStream(socket.getInputStream()); // boolean loop = true; // StringBuilder sb = new StringBuilder(8096); // while (loop) { // if (in.ready()) { // int i = 0; // while (i != -1) { // i = in.read(); // sb.append((char) i); // } // loop = false; // } // } item.done(); socket.close(); } catch (IOException e) { e.printStackTrace(); item.failed(); } } else if ("nio".equals(config.client)) { URI uri = request.getURI(); item.sent(); String requestBody = "GET / HTTP/1.1\n" + "Host: " + uri.getHost() + ":" + uri.getPort() + "\n" + "Connection: Close\n\n"; try { InetSocketAddress addr = new InetSocketAddress(uri.getHost(), uri.getPort()); SocketChannel channel = SocketChannel.open(); channel.socket().setSoTimeout(5000); channel.connect(addr); ByteBuffer msg = ByteBuffer.wrap(requestBody.getBytes()); channel.write(msg); msg.clear(); ByteBuffer buf = ByteBuffer.allocate(1024); int count; while ((count = channel.read(buf)) != -1) { buf.flip(); byte[] bytes = new byte[count]; buf.get(bytes); buf.clear(); } channel.close(); item.done(); } catch (IOException e) { e.printStackTrace(); item.failed(); } } } } catch (InterruptedException e) { System.err.println("Worker thread [" + this.toString() + "] was interrupted: " + e.getMessage()); } }
From source file:com.cong.chenchong.wifi.manager.ProxyConnector.java
public JSONObject sendRequest(Socket socket, JSONObject request) throws JSONException { try {//from w w w. ja v a 2 s . co m if (socket == null) { // The server is probably shutting down // myLog.i("null socket in ProxyConnector.sendRequest()"); return null; } else { return sendRequest(socket.getInputStream(), socket.getOutputStream(), request); } } catch (IOException e) { // myLog.i("IOException in proxy sendRequest wrapper: " + e); return null; } }
From source file:com.cbsb.ftpserv.ProxyConnector.java
public JSONObject sendRequest(Socket socket, JSONObject request) throws JSONException { try {// w ww. j a v a 2 s . c o m if (socket == null) { // The server is probably shutting down myLog.i("null socket in ProxyConnector.sendRequest()"); return null; } else { return sendRequest(socket.getInputStream(), socket.getOutputStream(), request); } } catch (IOException e) { myLog.i("IOException in proxy sendRequest wrapper: " + e); return null; } }