List of usage examples for java.net Socket Socket
public Socket()
From source file:info.guardianproject.net.SocksSocketFactory.java
@Override public Socket createSocket() throws IOException { return new Socket(); }
From source file:net.grinder.util.NetworkUtils.java
public static InetAddress getAddressWithSocket(String byConnecting, int port) { Socket s = new Socket(); try {// w ww. j a v a 2 s . co m if (tryConnection(byConnecting, port, s)) { return s.getLocalAddress(); } } finally { IOUtils.closeQuietly(s); } return null; }
From source file:com.bfd.harpc.heartbeat.HeartBeatTask.java
/** * socket?// w w w .jav a 2s . co m * <p> * * @param serverNode */ private boolean checkSocket(ServerNode serverNode) { boolean isValid = false; Socket socket = null; try { InetSocketAddress socketAddress = new InetSocketAddress(serverNode.getIp(), serverNode.getPort()); socket = new Socket(); socket.connect(socketAddress, heartbeatTimeout); isValid = true; if (LOGGER.isDebugEnabled()) { LOGGER.debug("Heartbeat to remote " + serverNode.genAddress() + " success!"); } } catch (IOException e) { LOGGER.warn("Heartbeat to remote " + serverNode.genAddress() + " failure!", e); } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { LOGGER.warn(e.getMessage(), e); } } } return isValid; }
From source file:de.hshannover.f4.trust.iron.mapserver.communication.http.BasicAccessAuthenticationTest.java
@Override @Before//from w w w. java 2 s . c o m public void setUp() { // ugly, create a properties file "somewhere" for testing try { File f; do { testConf = "irond_test_" + System.nanoTime(); f = new File(testConf); } while (f.exists()); FileWriter fw = new FileWriter(f); BufferedWriter bw = new BufferedWriter(fw); bw.write("test:test"); bw.flush(); fw.close(); } catch (IOException e) { fail(e.getMessage()); } mServerConf = StubProvider.getServerConfStub(testConf); BasicAuthProvider provider = null; try { provider = new BasicAuthProviderPropImpl(mServerConf); } catch (ProviderInitializationException e) { fail("Cannot initialize the provider!"); } Socket s = new Socket(); mBasicAuth = new BasicChannelAuth(s, provider); }
From source file:com.digitalpebble.storm.crawler.protocol.http.HttpResponse.java
/** * Default public constructor.//from w ww . j a va 2 s .com * * @param http * @param url * @param knownMetadata * @throws IOException * @throws HttpException */ public HttpResponse(HttpProtocol http, URL url, Metadata knownMetadata) throws IOException, HttpException { this.http = http; this.url = url; Scheme scheme = null; if ("http".equals(url.getProtocol())) { scheme = Scheme.HTTP; } else if ("https".equals(url.getProtocol())) { scheme = Scheme.HTTPS; } else { throw new IOException("Unknown scheme (not http/https) for url:" + url); } String path = "".equals(url.getFile()) ? "/" : url.getFile(); // some servers will redirect a request with a host line like // "Host: <hostname>:80" to "http://<hpstname>/<orig_path>"- they // don't want the :80... String host = url.getHost(); int port; String portString; if (url.getPort() == -1) { if (scheme == Scheme.HTTP) { port = 80; } else { port = 443; } portString = ""; } else { port = url.getPort(); portString = ":" + port; } Socket socket = null; try { socket = new Socket(); // create the socket socket.setSoTimeout(http.getTimeout()); // connect String sockHost = http.useProxy() ? http.getProxyHost() : host; int sockPort = http.useProxy() ? http.getProxyPort() : port; InetSocketAddress sockAddr = new InetSocketAddress(sockHost, sockPort); socket.connect(sockAddr, http.getTimeout()); if (scheme == Scheme.HTTPS) { SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket, sockHost, sockPort, true); sslsocket.setUseClientMode(true); // Get the protocols and ciphers supported by this JVM Set<String> protocols = new HashSet<String>(Arrays.asList(sslsocket.getSupportedProtocols())); Set<String> ciphers = new HashSet<String>(Arrays.asList(sslsocket.getSupportedCipherSuites())); // Intersect with preferred protocols and ciphers protocols.retainAll(http.getTlsPreferredProtocols()); ciphers.retainAll(http.getTlsPreferredCipherSuites()); sslsocket.setEnabledProtocols(protocols.toArray(new String[protocols.size()])); sslsocket.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()])); sslsocket.startHandshake(); socket = sslsocket; } this.conf = http.getConf(); if (ConfUtils.getBoolean(conf, "store.ip.address", false) == true) { headers.setValue("_ip_", sockAddr.getAddress().getHostAddress()); } // make request OutputStream req = socket.getOutputStream(); StringBuffer reqStr = new StringBuffer("GET "); if (http.useProxy()) { reqStr.append(url.getProtocol() + "://" + host + portString + path); } else { reqStr.append(path); } reqStr.append(" HTTP/1.0\r\n"); reqStr.append("Host: "); reqStr.append(host); reqStr.append(portString); reqStr.append("\r\n"); reqStr.append("Accept-Encoding: x-gzip, gzip, deflate\r\n"); String userAgent = http.getUserAgent(); if ((userAgent == null) || (userAgent.length() == 0)) { if (HttpProtocol.LOGGER.isErrorEnabled()) { HttpProtocol.LOGGER.error("User-agent is not set!"); } } else { reqStr.append("User-Agent: "); reqStr.append(userAgent); reqStr.append("\r\n"); } reqStr.append("Accept-Language: "); reqStr.append(this.http.getAcceptLanguage()); reqStr.append("\r\n"); reqStr.append("Accept: "); reqStr.append(this.http.getAccept()); reqStr.append("\r\n"); if (knownMetadata != null) { String ifModifiedSince = knownMetadata.getFirstValue("cachedLastModified"); if (StringUtils.isNotBlank(ifModifiedSince)) { reqStr.append("If-Modified-Since: "); reqStr.append(ifModifiedSince); reqStr.append("\r\n"); } String ifNoneMatch = knownMetadata.getFirstValue("cachedEtag"); if (StringUtils.isNotBlank(ifNoneMatch)) { reqStr.append("If-None-Match: "); reqStr.append(ifNoneMatch); reqStr.append("\r\n"); } } reqStr.append("\r\n"); // @see http://www.w3.org/Protocols/rfc2068/rfc2068.txt for default // charset // TODO use UTF-8 and set a charset value explicitely byte[] reqBytes = reqStr.toString().getBytes(StandardCharsets.ISO_8859_1); req.write(reqBytes); req.flush(); PushbackInputStream in = // process response new PushbackInputStream( new BufferedInputStream(socket.getInputStream(), HttpProtocol.BUFFER_SIZE), HttpProtocol.BUFFER_SIZE); StringBuffer line = new StringBuffer(); boolean haveSeenNonContinueStatus = false; while (!haveSeenNonContinueStatus) { // parse status code line this.code = parseStatusLine(in, line); // parse headers parseHeaders(in, line); haveSeenNonContinueStatus = code != 100; // 100 is // "Continue" } String transferEncoding = getHeader(HttpHeaders.TRANSFER_ENCODING); if (transferEncoding != null && "chunked".equalsIgnoreCase(transferEncoding.trim())) { readChunkedContent(in, line); } else { readPlainContent(in); } String contentEncoding = getHeader(HttpHeaders.CONTENT_ENCODING); if ("gzip".equals(contentEncoding) || "x-gzip".equals(contentEncoding)) { content = http.processGzipEncoded(content, url); } else if ("deflate".equals(contentEncoding)) { content = http.processDeflateEncoded(content, url); } else { HttpProtocol.LOGGER.trace("fetched {} bytes from {}", content.length, url); } } finally { if (socket != null) socket.close(); } }
From source file:edu.vt.middleware.gator.server.SocketServerTest.java
/** * Tests connecting to the socket server and sending a logging event that * should be written to configured appenders. * * @throws Exception On errors.//from w w w .j ava 2s. com */ @Test public void testConnectAndLog() throws Exception { final Socket sock = new Socket(); try { final SocketAddress addr = new InetSocketAddress(InetAddress.getByName(server.getBindAddress()), server.getPort()); sock.connect(addr, SOCKET_CONNECT_TIMEOUT); // Allow the socket server time to build the hierarchy // before sending a test logging event Thread.sleep(2000); Assert.assertEquals(1, server.getLoggingEventHandlers().size()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Sending test logging event."); } final ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream()); oos.writeObject(new MockEvent(TEST_MESSAGE)); oos.flush(); } finally { if (sock.isConnected()) { sock.close(); } } // Pause to allow time for logging events to be written Thread.sleep(2000); // Client socket close should trigger cleanup of server handler mapping Assert.assertEquals(0, server.getLoggingEventHandlers().size()); // Ensure test message was written to file Assert.assertTrue(readTextFile(LOG_FILE).contains(TEST_MESSAGE)); }
From source file:ee.ria.xroad.proxy.clientproxy.FastestConnectionSelectingSSLSocketFactory.java
@Override public Socket createSocket(HttpContext context) throws IOException { // create dummy socket that will be discarded return new Socket(); }
From source file:gobblin.tunnel.ConnectProxyServer.java
@Override void handleClientSocket(Socket clientSocket) throws IOException { final InputStream clientToProxyIn = clientSocket.getInputStream(); BufferedReader clientToProxyReader = new BufferedReader(new InputStreamReader(clientToProxyIn)); final OutputStream clientToProxyOut = clientSocket.getOutputStream(); String line = clientToProxyReader.readLine(); String connectRequest = ""; while (line != null && isServerRunning()) { connectRequest += line + "\r\n"; if (connectRequest.endsWith("\r\n\r\n")) { break; }/*w w w . j a v a2 s . c om*/ line = clientToProxyReader.readLine(); } // connect to given host:port Matcher matcher = hostPortPattern.matcher(connectRequest); if (!matcher.find()) { try { sendConnectResponse("400 Bad Request", clientToProxyOut, null, 0); } finally { clientSocket.close(); stopServer(); } return; } String host = matcher.group(1); int port = Integer.decode(matcher.group(2)); // connect to server Socket serverSocket = new Socket(); try { serverSocket.connect(new InetSocketAddress(host, port)); addSocket(serverSocket); byte[] initialServerResponse = null; int nbytes = 0; if (mixServerAndProxyResponse) { // we want to mix the initial server response with the 200 OK initialServerResponse = new byte[64]; nbytes = serverSocket.getInputStream().read(initialServerResponse); } sendConnectResponse("200 OK", clientToProxyOut, initialServerResponse, nbytes); } catch (IOException e) { try { sendConnectResponse("404 Not Found", clientToProxyOut, null, 0); } finally { clientSocket.close(); stopServer(); } return; } final InputStream proxyToServerIn = serverSocket.getInputStream(); final OutputStream proxyToServerOut = serverSocket.getOutputStream(); _threads.add(new EasyThread() { @Override void runQuietly() throws Exception { try { IOUtils.copy(clientToProxyIn, proxyToServerOut); } catch (IOException e) { LOG.warn("Exception " + e.getMessage() + " on " + getServerSocketPort()); } } }.startThread()); try { if (nBytesToCloseSocketAfter > 0) { // Simulate proxy abruptly closing connection int leftToRead = nBytesToCloseSocketAfter; byte[] buffer = new byte[leftToRead + 256]; while (true) { int numRead = proxyToServerIn.read(buffer, 0, leftToRead); if (numRead < 0) { break; } clientToProxyOut.write(buffer, 0, numRead); clientToProxyOut.flush(); leftToRead -= numRead; if (leftToRead <= 0) { LOG.warn("Cutting connection after " + nBytesToCloseSocketAfter + " bytes"); break; } } } else { IOUtils.copy(proxyToServerIn, clientToProxyOut); } } catch (IOException e) { LOG.warn("Exception " + e.getMessage() + " on " + getServerSocketPort()); } clientSocket.close(); serverSocket.close(); }
From source file:com.rapplogic.aru.uploader.wifi.WifiSketchUploader.java
@Override protected void open(final Map<String, Object> context) throws Exception { String host = (String) context.get("host"); Integer port = (Integer) context.get("port"); Integer connectionTimeoutSecs = (Integer) context.get("connectionTimeoutSecs"); Integer readTimeoutSecs = (Integer) context.get("readTimeoutSecs"); // open socket socket = new Socket(); socket.connect(new InetSocketAddress(host, port), connectionTimeoutSecs * 1000); socket.setSoTimeout(readTimeoutSecs * 1000); connected = true;/*from w ww . ja v a2 s.com*/ final int[] reply = new int[5]; final AtomicInteger replyIndex = new AtomicInteger(0); // TODO unlike other wireless protocols, wifi is stateful so we need to handle situations where we lose the socket and reconnect t = new Thread(new Runnable() { @Override public void run() { int ch = 0; // reply always terminated with 13,10 try { while ((ch = socket.getInputStream().read()) > -1) { if (replyIndex.get() < reply.length) { reply[replyIndex.getAndIncrement()] = ch; } else if (replyIndex.get() == 5 && ch == 13) { replyIndex.getAndIncrement(); // discard } else if (replyIndex.get() == 6 && ch == 10) { //System.out.println("reply is " + stringBuilder.toString()); // stringBuilder = new StringBuilder(); handleReply(reply); replyIndex.set(0); } else { //error throw new RuntimeException("Expected CR/LF -- invalid reply at position " + replyIndex.get() + ", array: " + intArrayToString(reply)); } } } catch (IOException e) { if (!connected && e instanceof SocketException) { // expected.. ignore } else { System.out.println("IO error in socket reader"); e.printStackTrace(); } } catch (Exception e) { System.out.println("Unexpected error in socket reader"); e.printStackTrace(); } connected = false; } }); t.setDaemon(true); t.start(); }
From source file:io.aino.agents.core.AgentIntegrationTest.java
private boolean isReachable(String host, int port, int timeout) throws IOException { SocketAddress proxyAddress = new InetSocketAddress(host, port); Socket socket = new Socket(); try {/* w w w.j a va2 s.c om*/ socket.connect(proxyAddress, timeout); //System.out.println("Connected to: " + host + ":" + port); return socket.isConnected(); } catch (IOException e) { System.out.println("Could not connect to: " + host + ":" + port); return false; } finally { if (socket.isConnected()) { //System.out.println("Closing connection to: " + host + ":" + port); socket.close(); //System.out.println("Disconnected: " + host + ":" + port); } } }