List of usage examples for java.net Socket setTcpNoDelay
public void setTcpNoDelay(boolean on) throws SocketException
From source file:org.cloudata.core.commitlog.CommitLogClient.java
public void open() throws UnmatchedLogException, CommitLogInterruptedException, IOException { pipeKey = generateUniqueKey();/*w w w . j av a2 s .c o m*/ if (LOG.isDebugEnabled()) { String msg = ""; for (String addr : ipAddressList) { msg = msg + addr + ", "; } LOG.debug("Open new pipe with timeout[" + this.timeout + "], key [" + pipeKey + "], -> " + msg); } String ret = null; Socket s = null; try { sc = SocketChannel.open(); s = sc.socket(); s.setTcpNoDelay(true); s.setSoTimeout(timeout); int addressIndex = 0; if (verifiedAddressIndex >= 0) { addressIndex = verifiedAddressIndex; } LOG.debug("open pipe to " + pipeAddressList[addressIndex]); sc.connect(pipeAddressList[addressIndex]); } catch (ClosedByInterruptException e) { internalClose(); throw new CommitLogInterruptedException(); } catch (IOException e) { throw new CommitLogShutDownException(e); } try { byte[] body = buildBody(); currentStream = new DataOutputStream(new BufferedOutputStream(s.getOutputStream(), 8192)); checkInputStream = new DataInputStream(s.getInputStream()); currentStream.write(MAGIC_KEY); currentStream.writeInt(0); currentStream.writeInt(body.length); currentStream.write(body); currentStream.flush(); DataInputStream dis = new DataInputStream(s.getInputStream()); byte[] key = new byte[MAGIC_KEY.length]; if (dis.read(key) < 0) { throw new IOException("Fail to establish pipe connection to " + getPipeAddressListStr()); } if (!Arrays.equals(MAGIC_KEY, key)) { throw new IOException( "Fail to establish pipe connection to " + getPipeAddressList() + "due to wrong magic key"); } int opCode = dis.readInt(); int replyLength = dis.readInt(); body = new byte[replyLength]; dis.read(body); ret = new String(body); } catch (ClosedByInterruptException e) { internalClose(); throw new CommitLogInterruptedException(); } catch (IOException e) { LOG.warn("Fail to establish pipe to " + getPipeAddressListStr() + " due to " + e, e); internalClose(); throw new IOException("Fail to establish pipe connection to " + getPipeAddressListStr(), e); } if (!ret.equals(Constants.PIPE_CONNECTED)) { internalClose(); if (ret.equals("Log files are unmatched among commit log servers")) { throw new UnmatchedLogException("Log files are unmatched among commit log servers"); } throw new IOException( "Fail to establish pipe connection to " + getPipeAddressListStr() + ". response : " + ret); } else { closed = false; } }
From source file:edu.hawaii.soest.kilonalu.tchain.TChainSource.java
/** * A method used to the TCP socket of the remote source host for communication * @param host the name or IP address of the host to connect to for the * socket connection (reading) * @param portNumber the number of the TCP port to connect to (i.e. 2604) *///from ww w.ja va 2 s .c om protected SocketChannel getSocketConnection() { String host = getHostName(); int portNumber = new Integer(getHostPort()).intValue(); SocketChannel dataSocket = null; try { // create the socket channel connection to the data source via the // converter serial2IP converter dataSocket = SocketChannel.open(); Socket tcpSocket = dataSocket.socket(); tcpSocket.setTcpNoDelay(true); tcpSocket.setReceiveBufferSize(40); dataSocket.connect(new InetSocketAddress(host, portNumber)); // if the connection to the source fails, also disconnect from the RBNB // server and return null if (!dataSocket.isConnected()) { dataSocket.close(); disconnect(); dataSocket = null; } } catch (UnknownHostException ukhe) { System.err.println("Unable to look up host: " + host + "\n"); disconnect(); dataSocket = null; } catch (IOException nioe) { System.err.println("Couldn't get I/O connection to: " + host); disconnect(); dataSocket = null; } catch (Exception e) { disconnect(); dataSocket = null; } return dataSocket; }
From source file:hudson.TcpSlaveAgentListener.java
@Override public void run() { try {/*from w ww . j a v a 2 s . c o m*/ // the loop eventually terminates when the socket is closed. while (!shuttingDown) { Socket s = serverSocket.accept().socket(); // this prevents a connection from silently terminated by the router in between or the other peer // and that goes without unnoticed. However, the time out is often very long (for example 2 hours // by default in Linux) that this alone is enough to prevent that. s.setKeepAlive(true); // we take care of buffering on our own s.setTcpNoDelay(true); new ConnectionHandler(s, new ConnectionHandlerFailureCallback(this) { @Override public void run(Throwable cause) { LOGGER.log(Level.WARNING, "Connection handler failed, restarting listener", cause); shutdown(); TcpSlaveAgentListenerRescheduler.schedule(getParentThread(), cause); } }).start(); } } catch (IOException e) { if (!shuttingDown) { LOGGER.log(Level.SEVERE, "Failed to accept TCP connections", e); } } }
From source file:org.apache.jk.common.ChannelSocket.java
public void accept(MsgContext ep) throws IOException { if (sSocket == null) return;/*from w w w.j a v a 2 s . c om*/ Socket s = sSocket.accept(); ep.setNote(socketNote, s); if (log.isDebugEnabled()) log.debug("Accepted socket " + s); if (linger > 0) s.setSoLinger(true, linger); if (socketTimeout > 0) s.setSoTimeout(socketTimeout); s.setTcpNoDelay(tcpNoDelay); // set socket tcpnodelay state requestCount++; InputStream is = new BufferedInputStream(s.getInputStream()); OutputStream os; if (BUFFER_WRITE) os = new BufferedOutputStream(s.getOutputStream()); else os = s.getOutputStream(); ep.setNote(isNote, is); ep.setNote(osNote, os); ep.setControl(tp); }
From source file:net.lightbody.bmp.proxy.jetty.http.ajp.AJP13Listener.java
/** * Handle Job. Implementation of ThreadPool.handle(), calls * handleConnection.//w ww .j av a 2s . co m * * @param socket * A Connection. */ public void handleConnection(Socket socket) throws IOException { // Check acceptable remote servers if (_remoteServers != null && _remoteServers.length > 0) { boolean match = false; InetAddress inetAddress = socket.getInetAddress(); String hostAddr = inetAddress.getHostAddress(); String hostName = inetAddress.getHostName(); for (int i = 0; i < _remoteServers.length; i++) { if (hostName.equals(_remoteServers[i]) || hostAddr.equals(_remoteServers[i])) { match = true; break; } } if (!match) { log.warn("AJP13 Connection from un-approved host: " + inetAddress); return; } } // Handle the connection socket.setTcpNoDelay(true); socket.setSoTimeout(getMaxIdleTimeMs()); AJP13Connection connection = createConnection(socket); try { connection.handle(); } finally { connection.destroy(); } }
From source file:org.openqa.selenium.server.ProxyHandler.java
protected HttpTunnel newHttpTunnel(HttpRequest request, HttpResponse response, InetAddress iaddr, int port, int timeoutMS) throws IOException { try {/*from w w w . j a v a2 s . c o m*/ 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(org.openqa.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; return new HttpTunnel(socket, in, null); } catch (IOException e) { log.debug(e); response.sendError(HttpResponse.__400_Bad_Request); return null; } }
From source file:hudson.cli.CLI.java
/** * @deprecated Specific to {@link Mode#REMOTING}. *///from w w w. j ava 2s . co m @Deprecated private Channel connectViaCliPort(URL jenkins, CliPort clip) throws IOException { LOGGER.log(FINE, "Trying to connect directly via Remoting over TCP/IP to {0}", clip.endpoint); if (authorization != null) { LOGGER.warning("-auth ignored when using JNLP agent port"); } final Socket s = new Socket(); // this prevents a connection from silently terminated by the router in between or the other peer // and that goes without unnoticed. However, the time out is often very long (for example 2 hours // by default in Linux) that this alone is enough to prevent that. s.setKeepAlive(true); // we take care of buffering on our own s.setTcpNoDelay(true); OutputStream out; if (httpsProxyTunnel != null) { String[] tokens = httpsProxyTunnel.split(":"); LOGGER.log(Level.FINE, "Using HTTP proxy {0}:{1} to connect to CLI port", new Object[] { tokens[0], tokens[1] }); s.connect(new InetSocketAddress(tokens[0], Integer.parseInt(tokens[1]))); PrintStream o = new PrintStream(s.getOutputStream()); o.print("CONNECT " + clip.endpoint.getHostString() + ":" + clip.endpoint.getPort() + " HTTP/1.0\r\n\r\n"); // read the response from the proxy ByteArrayOutputStream rsp = new ByteArrayOutputStream(); while (!rsp.toString("ISO-8859-1").endsWith("\r\n\r\n")) { int ch = s.getInputStream().read(); if (ch < 0) throw new IOException("Failed to read the HTTP proxy response: " + rsp); rsp.write(ch); } String head = new BufferedReader(new StringReader(rsp.toString("ISO-8859-1"))).readLine(); if (head == null) { throw new IOException("Unexpected empty response"); } if (!(head.startsWith("HTTP/1.0 200 ") || head.startsWith("HTTP/1.1 200 "))) { s.close(); LOGGER.log(Level.SEVERE, "Failed to tunnel the CLI port through the HTTP proxy. Falling back to HTTP."); throw new IOException("Failed to establish a connection through HTTP proxy: " + rsp); } // HTTP proxies (at least the one I tried --- squid) doesn't seem to do half-close very well. // So instead of relying on it, we'll just send the close command and then let the server // cut their side, then close the socket after the join. out = new SocketOutputStream(s) { @Override public void close() throws IOException { // ignore } }; } else { s.connect(clip.endpoint, 3000); out = SocketChannelStream.out(s); } closables.add(new Closeable() { public void close() throws IOException { s.close(); } }); Connection c = new Connection(SocketChannelStream.in(s), out); switch (clip.version) { case 1: DataOutputStream dos = new DataOutputStream(s.getOutputStream()); dos.writeUTF("Protocol:CLI-connect"); // we aren't checking greeting from the server here because I'm too lazy. It gets ignored by Channel constructor. break; case 2: DataInputStream dis = new DataInputStream(s.getInputStream()); dos = new DataOutputStream(s.getOutputStream()); dos.writeUTF("Protocol:CLI2-connect"); String greeting = dis.readUTF(); if (!greeting.equals("Welcome")) throw new IOException("Handshaking failed: " + greeting); try { byte[] secret = c.diffieHellman(false).generateSecret(); SecretKey sessionKey = new SecretKeySpec(Connection.fold(secret, 128 / 8), "AES"); c = c.encryptConnection(sessionKey, "AES/CFB8/NoPadding"); // validate the instance identity, so that we can be sure that we are talking to the same server // and there's no one in the middle. byte[] signature = c.readByteArray(); if (clip.identity != null) { Signature verifier = Signature.getInstance("SHA1withRSA"); verifier.initVerify(clip.getIdentity()); verifier.update(secret); if (!verifier.verify(signature)) throw new IOException("Server identity signature validation failed."); } } catch (GeneralSecurityException e) { throw (IOException) new IOException("Failed to negotiate transport security").initCause(e); } } return new Channel("CLI connection to " + jenkins, pool, new BufferedInputStream(c.in), new BufferedOutputStream(c.out)); }
From source file:com.sun.grizzly.http.jk.common.ChannelNioSocket.java
private void setSocketOptions(Socket s) throws SocketException { if (socketTimeout > 0) { s.setSoTimeout(socketTimeout);/*from w w w .j a va2s. co m*/ } s.setTcpNoDelay(tcpNoDelay); // set socket tcpnodelay state if (linger > 0) { s.setSoLinger(true, linger); } }
From source file:org.mule.transport.tcp.TcpConnector.java
public void configureSocket(boolean client, Socket socket) throws SocketException { // There is some overhead in setting socket timeout and buffer size, so we're // careful here only to set if needed if (newValue(getReceiveBufferSize(), socket.getReceiveBufferSize())) { socket.setReceiveBufferSize(getReceiveBufferSize()); }//from w w w . j a v a2 s .c o m if (newValue(getSendBufferSize(), socket.getSendBufferSize())) { socket.setSendBufferSize(getSendBufferSize()); } if (client) { if (newValue(getClientSoTimeout(), socket.getSoTimeout())) { socket.setSoTimeout(getClientSoTimeout()); } } else { if (newValue(getServerSoTimeout(), socket.getSoTimeout())) { socket.setSoTimeout(getServerSoTimeout()); } } if (newValue(getSocketSoLinger(), socket.getSoLinger())) { socket.setSoLinger(true, getSocketSoLinger()); } try { socket.setTcpNoDelay(isSendTcpNoDelay()); } catch (SocketException e) { // MULE-2800 - Bug in Solaris } socket.setKeepAlive(isKeepAlive()); }
From source file:com.mobilyzer.util.PhoneUtils.java
/** * Using MLab service to detect ipv4 or ipv6 compatibility * @param ip_detect_type -- "ipv4" or "ipv6" * @return IP_TYPE_CANNOT_DECIDE, IP_TYPE_UNCONNECTIVITY, IP_TYPE_CONNECTIVITY *///from ww w . j a va 2 s . c o m private int checkIPCompatibility(String ip_detect_type) { if (!ip_detect_type.equals("ipv4") && !ip_detect_type.equals("ipv6")) { return IP_TYPE_CANNOT_DECIDE; } Socket tcpSocket = new Socket(); try { ArrayList<String> hostnameList = MLabNS.Lookup(context, "mobiperf", ip_detect_type, "ip"); // MLabNS returns at least one ip address if (hostnameList.isEmpty()) return IP_TYPE_CANNOT_DECIDE; // Use the first result in the element String hostname = hostnameList.get(0); SocketAddress remoteAddr = new InetSocketAddress(hostname, portNum); tcpSocket.setTcpNoDelay(true); tcpSocket.connect(remoteAddr, tcpTimeout); } catch (ConnectException e) { // Server is not reachable due to client not support ipv6 Logger.e("Connection exception is " + e.getMessage()); return IP_TYPE_UNCONNECTIVITY; } catch (IOException e) { // Client timer expired Logger.e("Fail to setup TCP in checkIPCompatibility(). " + e.getMessage()); return IP_TYPE_CANNOT_DECIDE; } catch (InvalidParameterException e) { // MLabNS service lookup fail Logger.e("InvalidParameterException in checkIPCompatibility(). " + e.getMessage()); return IP_TYPE_CANNOT_DECIDE; } catch (IllegalArgumentException e) { Logger.e("IllegalArgumentException in checkIPCompatibility(). " + e.getMessage()); return IP_TYPE_CANNOT_DECIDE; } finally { try { tcpSocket.close(); } catch (IOException e) { Logger.e("Fail to close TCP in checkIPCompatibility()."); return IP_TYPE_CANNOT_DECIDE; } } return IP_TYPE_CONNECTIVITY; }