Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
As a follow up to a recent question, I wonder why it is impossible in Java, without attempting reading/writing on a TCP socket, to detect that the socket has been gracefully closed by the peer? This seems to be the case regardless of whether one uses the pre-NIO Socket or the NIO SocketChannel. When a peer gracefully closes a TCP connection, the TCP stacks on both sides of the connection know ...
How do you detect if Socket#close() has been called on a socket on the remote side?
Given this stack trace snippet Caused by: java.net.SocketException: Software caused connection abort: socket write error  at java.net.SocketOutputStream.socketWrite0(Native Method) I tried to answer the following questions: What code is throwing this exception? (JVM?/Tomcat?/My code?) What causes this exception to be thrown? Regarding #1: Sun's JVM source doesn't contai...
I'm looking to develop two separate (but related) Java desktop applications. I want the ability for one application to trigger the other, passing in data that can then be edited and passed back, i.e. the communication will be two way. If the other application is already running I want them to just communicate, i.e. I dont want to just pass arguments over the command line, etc. Generally spea...
I'm using a Java socket client. In a case where the server is still connected to my client but it does not send a response to my message - I eventually get a read time out exception. In that case I want to test to see if I should reconnect my socket or just keep it an re-use it. I use this condition: if (!socket.isConnected() || socket.isClosed() || !socket.isBound()) { try { soc...
I am trying to write a simple networked chat program in Java. I have almost no networking experience. I was wondering what resources I should begin looking at (beside here of course). Sticking with the core Java API would be best for now.
I just wondering what java does when we call close on the inputStream and outStream associated with a socket. What is the difference from the close call on the socket, i.e Socket.close(). if we just close the io stream on the socket, but not close the socket, can we reopen the io stream on the socket again? Thanks in advance!
Have seen this comment in a method: //I wonder why Sun made input and output streams implement Closeable and left Socket behind It would prevent creation of wrapper anonymous inner class which implements Closeable which delegates its close method to an instance of Socket.
What's the best way of using Unix domain sockets from Scala? I've found a Java library called JUDS, but it doesn't appear to allow me to send file descriptors over the socket --- the reason I want to use Unix domain sockets in the first place. The JUDS readme refers to a competing library called J-BUDS, but I cannot find this anywhere. I could add the feature to JUDS myself, but I'd rather I...
When using a Socket class one is establishing a TCP connection to a server on some port, but on the server the ServerSocket is capable of handling multiple client connections for each accept request and delegate it to a thread to server the request. But how is it possible for a ServerSocket class to accept multiple tcp connections on the same port. Does it mean that it is upto the OS to deci...
If you create a TCP client socket with port 0 instead of a non-zero port, then the operating system chooses any free ephemeral port for you. Most OSes choose ephemeral ports from the IANA dynamic port range of 49152-65535. However in Windows Server 2003 and earlier (including XP) Microsoft used ports 1025-5000 as the ephemeral range, according to their bind() documentation. I run multiple Ja...
Hi I am writing an application for a device -- tablet -- running windows 7. The application is being written in java. The application needs to be aware of which networking adapter is available (WIFI, 3G, etc ...) Is there a java library similar to the one developed for android -- android.net, android.net.wifi, etc ... -- In brief, How can a java application running on windows 7 choose which ...
I want to implement an SSL proxy in Java. I basically open two sockets browser-proxy,proxy-server, and run two threads which would write to proxy-server what they read from browser-proxy, and vice versa. Each thread looks like this: while (true) { nr = in.read(buffer); if (nr == -1) System.out.println(sockin.toString()+" EOF "+nr); if (nr == -1) break; out.write(buffer, 0, nr); } ...
I have heard of HTTP keep-alive but for now I want to open a socket connection with a remote server. Now will this socket connection remain open forever or is there a timeout limit associated with it similar to HTTP keep-alive?
Is there any kind of difference between 1) DocumentBuilder.parse(InputStream) and 2) DocumentBuilder.parse(InputSource)? I could only find that for the first case, the parser detects the encoding from the stream so it is safer while in the latter I am not sure if it is required to set the encoding. Any other points (e.g. performance) I should be aware? Thanks
Does anybody know how to receive (how to know that you received) out-of-band data with Java sockets? In particular I've read the documentation for sendUrgentData and setOOBInline which states that: Note, only limited support is provided for handling incoming urgent data. In particular, no notification of incoming urgent data is provided and there is no capability to distinguish between norm...
I hope you can help. Im fairly new to progamming and Im playing around with java Sockets. The problem is the code below. for some reason commSocket = new Socket(hostName, portNumber); is returning true even when it has not connected with the server (server not implemented yet!). Any ideas regarding this situation? For hostName Im passing my local machine IP and for port a manually selected po...
I have a test application that opens a socket , sends something through this socket and then closes it . This is done in a loop for 5-10.000 times. The thing is that after 3,4000 iterations I get an error of this type : java.net.BindException: Address already in use: connect I even set the socket to be used immediattly, but the error persists try { out_server.write(m.ToByteArray()); ...
I am working on a project and have a question about Java sockets. The source file which can be found here. After successfully transmitting the file size in plain text I need to transfer binary data. (DVD .Vob files) I have a loop such as // Read this files size long fileSize = Integer.parseInt(in.readLine()); // Read the block size they are go...
I have a single-threaded non-blocking socket IO server written in Java using nio. When I have finished writing to a connection, I want to close it. Does the closing of the channel mean blocking until all buffered writes have been acknowledged by the recipient? It would be useful to know if, when asynchronously closing, it succeeded or not, but I could live with any errors in the closing bein...
In Java, how would you set up a socket listener that listened to a socket for a series of bytes that represented a command and on recieving called a method which parsed the incoming data and invoked the appropriate command? Clarification: My issue is not with handling the commands (Which might also be error codes or responses to commands from the server) but with creating the socket and liste...
   /*
    * Copyright 1995-2007 Sun Microsystems, Inc.  All Rights Reserved.
    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    *
    * This code is free software; you can redistribute it and/or modify it
    * under the terms of the GNU General Public License version 2 only, as
    * published by the Free Software Foundation.  Sun designates this
    * particular file as subject to the "Classpath" exception as provided
    * by Sun in the LICENSE file that accompanied this code.
   *
   * This code is distributed in the hope that it will be useful, but WITHOUT
   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   * version 2 for more details (a copy is included in the LICENSE file that
   * accompanied this code).
   *
   * You should have received a copy of the GNU General Public License version
   * 2 along with this work; if not, write to the Free Software Foundation,
   * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   *
   * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
   * CA 95054 USA or visit www.sun.com if you need additional information or
   * have any questions.
   */
  
  package java.net;
  
This class implements client sockets (also called just "sockets"). A socket is an endpoint for communication between two machines.

The actual work of the socket is performed by an instance of the SocketImpl class. An application, by changing the socket factory that creates the socket implementation, can configure itself to create sockets appropriate to the local firewall.

  
  public
  class Socket {
    
Various states of this socket.
  
      private boolean created = false;
      private boolean bound = false;
      private boolean connected = false;
      private boolean closed = false;
      private Object closeLock = new Object();
      private boolean shutIn = false;
      private boolean shutOut = false;

    
The implementation of this Socket.
  
      SocketImpl impl;

    
Are we using an older SocketImpl?
  
      private boolean oldImpl = false;

    
Creates an unconnected socket, with the system-default type of SocketImpl.

Since:
JDK1.1
Revised:
1.4
  
      public Socket() {
          setImpl();
      }

    
Creates an unconnected socket, specifying the type of proxy, if any, that should be used regardless of any other settings.

If there is a security manager, its checkConnect method is called with the proxy host address and port number as its arguments. This could result in a SecurityException.

Examples:

  • Socket s = new Socket(Proxy.NO_PROXY); will create a plain socket ignoring any other proxy configuration.
  • Socket s = new Socket(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("socks.mydom.com", 1080))); will create a socket connecting through the specified SOCKS proxy server.

Parameters:
proxy a Proxy object specifying what kind of proxying should be used.
Throws:
java.lang.IllegalArgumentException if the proxy is of an invalid type or null.
java.lang.SecurityException if a security manager is present and permission to connect to the proxy is denied.
Since:
1.5
See also:
ProxySelector
Proxy
 
     public Socket(Proxy proxy) {
         if (proxy != null && proxy.type() == ..) {
             SecurityManager security = System.getSecurityManager();
             InetSocketAddress epoint = (InetSocketAddressproxy.address();
             if (security != null) {
                 if (epoint.isUnresolved())
                     epoint = new InetSocketAddress(epoint.getHostName(), epoint.getPort());
                 if (epoint.isUnresolved())
                     security.checkConnect(epoint.getHostName(),
                                           epoint.getPort());
                 else
                     security.checkConnect(epoint.getAddress().getHostAddress(),
                                           epoint.getPort());
             }
              = new SocksSocketImpl(proxy);
             .setSocket(this);
         } else {
             if (proxy == .) {
                 if ( == null) {
                      = new PlainSocketImpl();
                     .setSocket(this);
                 } else
                     setImpl();
             } else
                 throw new IllegalArgumentException("Invalid Proxy");
         }
     }

    
Creates an unconnected Socket with a user-specified SocketImpl.

Parameters:
impl an instance of a SocketImpl the subclass wishes to use on the Socket.
Throws:
SocketException if there is an error in the underlying protocol, such as a TCP error.
Since:
JDK1.1
 
     protected Socket(SocketImpl implthrows SocketException {
         this. = impl;
         if (impl != null) {
             checkOldImpl();
             this..setSocket(this);
         }
     }

    
Creates a stream socket and connects it to the specified port number on the named host.

If the specified host is null it is the equivalent of specifying the address as InetAddress.getByName(null). In other words, it is equivalent to specifying an address of the loopback interface.

If the application has specified a server socket factory, that factory's createSocketImpl method is called to create the actual socket implementation. Otherwise a "plain" socket is created.

If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.

Parameters:
host the host name, or null for the loopback address.
port the port number.
Throws:
UnknownHostException if the IP address of the host could not be determined.
java.io.IOException if an I/O error occurs when creating the socket.
java.lang.SecurityException if a security manager exists and its checkConnect method doesn't allow the operation.
See also:
setSocketImplFactory(java.net.SocketImplFactory)
SocketImpl
SocketImplFactory.createSocketImpl()
java.lang.SecurityManager.checkConnect(java.lang.String,int)
 
     public Socket(String hostint port)
         throws UnknownHostExceptionIOException
     {
         this(host != null ? new InetSocketAddress(hostport) :
              new InetSocketAddress(InetAddress.getByName(null), port),
              (SocketAddressnulltrue);
     }

    
Creates a stream socket and connects it to the specified port number at the specified IP address.

If the application has specified a socket factory, that factory's createSocketImpl method is called to create the actual socket implementation. Otherwise a "plain" socket is created.

If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.

Parameters:
address the IP address.
port the port number.
Throws:
java.io.IOException if an I/O error occurs when creating the socket.
java.lang.SecurityException if a security manager exists and its checkConnect method doesn't allow the operation.
See also:
setSocketImplFactory(java.net.SocketImplFactory)
SocketImpl
SocketImplFactory.createSocketImpl()
java.lang.SecurityManager.checkConnect(java.lang.String,int)
 
     public Socket(InetAddress addressint portthrows IOException {
         this(address != null ? new InetSocketAddress(addressport) : null,
              (SocketAddressnulltrue);
     }

    
Creates a socket and connects it to the specified remote host on the specified remote port. The Socket will also bind() to the local address and port supplied.

If the specified host is null it is the equivalent of specifying the address as InetAddress.getByName(null). In other words, it is equivalent to specifying an address of the loopback interface.

If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.

Parameters:
host the name of the remote host, or null for the loopback address.
port the remote port
localAddr the local address the socket is bound to
localPort the local port the socket is bound to
Throws:
java.io.IOException if an I/O error occurs when creating the socket.
java.lang.SecurityException if a security manager exists and its checkConnect method doesn't allow the operation.
Since:
JDK1.1
See also:
java.lang.SecurityManager.checkConnect(java.lang.String,int)
 
     public Socket(String hostint portInetAddress localAddr,
                   int localPortthrows IOException {
         this(host != null ? new InetSocketAddress(hostport) :
                new InetSocketAddress(InetAddress.getByName(null), port),
              new InetSocketAddress(localAddrlocalPort), true);
     }

    
Creates a socket and connects it to the specified remote address on the specified remote port. The Socket will also bind() to the local address and port supplied.

If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.

Parameters:
address the remote address
port the remote port
localAddr the local address the socket is bound to
localPort the local port the socket is bound to
Throws:
java.io.IOException if an I/O error occurs when creating the socket.
java.lang.SecurityException if a security manager exists and its checkConnect method doesn't allow the operation.
Since:
JDK1.1
See also:
java.lang.SecurityManager.checkConnect(java.lang.String,int)
 
     public Socket(InetAddress addressint portInetAddress localAddr,
                   int localPortthrows IOException {
         this(address != null ? new InetSocketAddress(addressport) : null,
              new InetSocketAddress(localAddrlocalPort), true);
     }

    
Creates a stream socket and connects it to the specified port number on the named host.

If the specified host is null it is the equivalent of specifying the address as InetAddress.getByName(null). In other words, it is equivalent to specifying an address of the loopback interface.

If the stream argument is true, this creates a stream socket. If the stream argument is false, it creates a datagram socket.

If the application has specified a server socket factory, that factory's createSocketImpl method is called to create the actual socket implementation. Otherwise a "plain" socket is created.

If there is a security manager, its checkConnect method is called with the host address and port as its arguments. This could result in a SecurityException.

If a UDP socket is used, TCP/IP related socket options will not apply.

Deprecated:
Use DatagramSocket instead for UDP transport.
Parameters:
host the host name, or null for the loopback address.
port the port number.
stream a boolean indicating whether this is a stream socket or a datagram socket.
Throws:
java.io.IOException if an I/O error occurs when creating the socket.
java.lang.SecurityException if a security manager exists and its checkConnect method doesn't allow the operation.
See also:
setSocketImplFactory(java.net.SocketImplFactory)
SocketImpl
SocketImplFactory.createSocketImpl()
java.lang.SecurityManager.checkConnect(java.lang.String,int)
 
     @Deprecated
     public Socket(String hostint portboolean streamthrows IOException {
         this(host != null ? new InetSocketAddress(hostport) :
                new InetSocketAddress(InetAddress.getByName(null), port),
              (SocketAddressnullstream);
     }

    
Creates a socket and connects it to the specified port number at the specified IP address.

If the stream argument is true, this creates a stream socket. If the stream argument is false, it creates a datagram socket.

If the application has specified a server socket factory, that factory's createSocketImpl method is called to create the actual socket implementation. Otherwise a "plain" socket is created.

If there is a security manager, its checkConnect method is called with host.getHostAddress() and port as its arguments. This could result in a SecurityException.

If UDP socket is used, TCP/IP related socket options will not apply.

Deprecated:
Use DatagramSocket instead for UDP transport.
Parameters:
host the IP address.
port the port number.
stream if true, create a stream socket; otherwise, create a datagram socket.
Throws:
java.io.IOException if an I/O error occurs when creating the socket.
java.lang.SecurityException if a security manager exists and its checkConnect method doesn't allow the operation.
See also:
setSocketImplFactory(java.net.SocketImplFactory)
SocketImpl
SocketImplFactory.createSocketImpl()
java.lang.SecurityManager.checkConnect(java.lang.String,int)
 
     @Deprecated
     public Socket(InetAddress hostint portboolean streamthrows IOException {
         this(host != null ? new InetSocketAddress(hostport) : null,
              new InetSocketAddress(0), stream);
     }
 
     private Socket(SocketAddress addressSocketAddress localAddr,
                    boolean streamthrows IOException {
         setImpl();
 
         // backward compatibility
         if (address == null)
             throw new NullPointerException();
 
         try {
             createImpl(stream);
             if (localAddr != null)
                 bind(localAddr);
             if (address != null)
                 connect(address);
         } catch (IOException e) {
             close();
             throw e;
         }
     }

    
Creates the socket implementation.

Parameters:
stream a boolean value : true for a TCP socket, false for UDP.
Throws:
java.io.IOException if creation fails
Since:
1.4
 
      void createImpl(boolean streamthrows SocketException {
         if ( == null)
             setImpl();
         try {
             .create(stream);
              = true;
         } catch (IOException e) {
             throw new SocketException(e.getMessage());
         }
     }
 
     private void checkOldImpl() {
         if ( == null)
             return;
         // SocketImpl.connect() is a protected method, therefore we need to use
         // getDeclaredMethod, therefore we need permission to access the member
 
          = AccessController.doPrivileged
                                 (new PrivilegedAction<Boolean>() {
             public Boolean run() {
                 Class[] cl = new Class[2];
                 cl[0] = SocketAddress.class;
                 cl[1] = .;
                 Class clazz = .getClass();
                 while (true) {
                     try {
                         clazz.getDeclaredMethod("connect"cl);
                         return .;
                     } catch (NoSuchMethodException e) {
                         clazz = clazz.getSuperclass();
                         // java.net.SocketImpl class will always have this abstract method.
                         // If we have not found it by now in the hierarchy then it does not
                         // exist, we are an old style impl.
                         if (clazz.equals(java.net.SocketImpl.class)) {
                             return .;
                         }
                     }
                 }
             }
         });
     }

    
Sets impl to the system-default type of SocketImpl.

Since:
1.4
 
     void setImpl() {
         if ( != null) {
              = .createSocketImpl();
             checkOldImpl();
         } else {
             // No need to do a checkOldImpl() here, we know it's an up to date
             // SocketImpl!
              = new SocksSocketImpl();
         }
         if ( != null)
             .setSocket(this);
     }


    
Get the SocketImpl attached to this socket, creating it if necessary.

Returns:
the SocketImpl attached to that ServerSocket.
Throws:
SocketException if creation fails
Since:
1.4
 
     SocketImpl getImpl() throws SocketException {
         if (!)
             createImpl(true);
         return ;
     }

    
Connects this socket to the server.

Parameters:
endpoint the SocketAddress
Throws:
java.io.IOException if an error occurs during the connection
java.nio.channels.IllegalBlockingModeException if this socket has an associated channel, and the channel is in non-blocking mode
java.lang.IllegalArgumentException if endpoint is null or is a SocketAddress subclass not supported by this socket
Since:
1.4
Spec:
JSR-51
 
     public void connect(SocketAddress endpointthrows IOException {
         connect(endpoint, 0);
     }

    
Connects this socket to the server with a specified timeout value. A timeout of zero is interpreted as an infinite timeout. The connection will then block until established or an error occurs.

Parameters:
endpoint the SocketAddress
timeout the timeout value to be used in milliseconds.
Throws:
java.io.IOException if an error occurs during the connection
SocketTimeoutException if timeout expires before connecting
java.nio.channels.IllegalBlockingModeException if this socket has an associated channel, and the channel is in non-blocking mode
java.lang.IllegalArgumentException if endpoint is null or is a SocketAddress subclass not supported by this socket
Since:
1.4
Spec:
JSR-51
 
     public void connect(SocketAddress endpointint timeoutthrows IOException {
         if (endpoint == null)
             throw new IllegalArgumentException("connect: The address can't be null");
 
         if (timeout < 0)
           throw new IllegalArgumentException("connect: timeout can't be negative");
 
         if (isClosed())
             throw new SocketException("Socket is closed");
 
         if (! && isConnected())
             throw new SocketException("already connected");
 
         if (!(endpoint instanceof InetSocketAddress))
             throw new IllegalArgumentException("Unsupported address type");
 
         InetSocketAddress epoint = (InetSocketAddressendpoint;
 
         SecurityManager security = System.getSecurityManager();
         if (security != null) {
             if (epoint.isUnresolved())
                 security.checkConnect(epoint.getHostName(),
                                       epoint.getPort());
             else
                 security.checkConnect(epoint.getAddress().getHostAddress(),
                                       epoint.getPort());
         }
         if (!)
             createImpl(true);
         if (!)
             .connect(epointtimeout);
         else if (timeout == 0) {
             if (epoint.isUnresolved())
                 .connect(epoint.getAddress().getHostName(),
                              epoint.getPort());
             else
                 .connect(epoint.getAddress(), epoint.getPort());
         } else
             throw new UnsupportedOperationException("SocketImpl.connect(addr, timeout)");
          = true;
         /*
          * If the socket was not bound before the connect, it is now because
          * the kernel will have picked an ephemeral port & a local address
          */
          = true;
     }

    
Binds the socket to a local address.

If the address is null, then the system will pick up an ephemeral port and a valid local address to bind the socket.

Parameters:
bindpoint the SocketAddress to bind to
Throws:
java.io.IOException if the bind operation fails, or if the socket is already bound.
java.lang.IllegalArgumentException if bindpoint is a SocketAddress subclass not supported by this socket
Since:
1.4
See also:
isBound()
 
     public void bind(SocketAddress bindpointthrows IOException {
         if (isClosed())
             throw new SocketException("Socket is closed");
         if (! && isBound())
             throw new SocketException("Already bound");
 
         if (bindpoint != null && (!(bindpoint instanceof InetSocketAddress)))
             throw new IllegalArgumentException("Unsupported address type");
         InetSocketAddress epoint = (InetSocketAddressbindpoint;
         if (epoint != null && epoint.isUnresolved())
             throw new SocketException("Unresolved address");
         if (bindpoint == null)
             getImpl().bind(InetAddress.anyLocalAddress(), 0);
         else
             getImpl().bind(epoint.getAddress(),
                            epoint.getPort());
          = true;
     }

    
set the flags after an accept() call.
 
     final void postAccept() {
          = true;
          = true;
          = true;
     }
 
     void setCreated() {
          = true;
     }
 
     void setBound() {
          = true;
     }
 
     void setConnected() {
          = true;
     }

    
Returns the address to which the socket is connected.

Returns:
the remote IP address to which this socket is connected, or null if the socket is not connected.
 
     public InetAddress getInetAddress() {
         if (!isConnected())
             return null;
         try {
             return getImpl().getInetAddress();
         } catch (SocketException e) {
         }
         return null;
     }

    
Gets the local address to which the socket is bound.

Returns:
the local address to which the socket is bound or InetAddress.anyLocalAddress() if the socket is not bound yet.
Since:
JDK1.1
 
     public InetAddress getLocalAddress() {
         // This is for backward compatibility
         if (!isBound())
             return InetAddress.anyLocalAddress();
         InetAddress in = null;
         try {
             in = (InetAddressgetImpl().getOption(.);
             if (in.isAnyLocalAddress()) {
                 in = InetAddress.anyLocalAddress();
             }
         } catch (Exception e) {
             in = InetAddress.anyLocalAddress(); // "0.0.0.0"
         }
         return in;
     }

    
Returns the remote port number to which this socket is connected.

Returns:
the remote port number to which this socket is connected, or 0 if the socket is not connected yet.
 
     public int getPort() {
         if (!isConnected())
             return 0;
         try {
             return getImpl().getPort();
         } catch (SocketException e) {
             // Shouldn't happen as we're connected
         }
         return -1;
     }

    
Returns the local port number to which this socket is bound.

Returns:
the local port number to which this socket is bound or -1 if the socket is not bound yet.
 
     public int getLocalPort() {
         if (!isBound())
             return -1;
         try {
             return getImpl().getLocalPort();
         } catch(SocketException e) {
             // shouldn't happen as we're bound
         }
         return -1;
     }

    
Returns the address of the endpoint this socket is connected to, or null if it is unconnected.

Returns:
a SocketAddress reprensenting the remote endpoint of this socket, or null if it is not connected yet.
Since:
1.4
See also:
getInetAddress()
getPort()
connect(java.net.SocketAddress,int)
connect(java.net.SocketAddress)
 
         if (!isConnected())
             return null;
         return new InetSocketAddress(getInetAddress(), getPort());
     }

    
Returns the address of the endpoint this socket is bound to, or null if it is not bound yet.

Returns:
a SocketAddress representing the local endpoint of this socket, or null if it is not bound yet.
Since:
1.4
See also:
getLocalAddress()
getLocalPort()
bind(java.net.SocketAddress)
 
 
     public SocketAddress getLocalSocketAddress() {
         if (!isBound())
             return null;
         return new InetSocketAddress(getLocalAddress(), getLocalPort());
     }

    
Returns the unique SocketChannel object associated with this socket, if any.

A socket will have a channel if, and only if, the channel itself was created via the SocketChannel.open or java.nio.channels.ServerSocketChannel.accept() methods.

Returns:
the socket channel associated with this socket, or null if this socket was not created for a channel
Since:
1.4
Spec:
JSR-51
 
     public SocketChannel getChannel() {
         return null;
     }

    
Returns an input stream for this socket.

If this socket has an associated channel then the resulting input stream delegates all of its operations to the channel. If the channel is in non-blocking mode then the input stream's read operations will throw an java.nio.channels.IllegalBlockingModeException.

Under abnormal conditions the underlying connection may be broken by the remote host or the network software (for example a connection reset in the case of TCP connections). When a broken connection is detected by the network software the following applies to the returned input stream :-

  • The network software may discard bytes that are buffered by the socket. Bytes that aren't discarded by the network software can be read using read.

  • If there are no bytes buffered on the socket, or all buffered bytes have been consumed by read, then all subsequent calls to read will throw an IOException.

  • If there are no bytes buffered on the socket, and the socket has not been closed using close, then available will return 0.

Closing the returned InputStream will close the associated socket.

Returns:
an input stream for reading bytes from this socket.
Throws:
java.io.IOException if an I/O error occurs when creating the input stream, the socket is closed, the socket is not connected, or the socket input has been shutdown using shutdownInput()
Revised:
1.4
Spec:
JSR-51
 
     public InputStream getInputStream() throws IOException {
         if (isClosed())
             throw new SocketException("Socket is closed");
         if (!isConnected())
             throw new SocketException("Socket is not connected");
         if (isInputShutdown())
             throw new SocketException("Socket input is shutdown");
         final Socket s = this;
         InputStream is = null;
         try {
             is = (InputStream)
                 AccessController.doPrivileged(new PrivilegedExceptionAction() {
                     public Object run() throws IOException {
                         return .getInputStream();
                     }
                 });
         } catch (java.security.PrivilegedActionException e) {
             throw (IOExceptione.getException();
         }
         return is;
     }

    
Returns an output stream for this socket.

If this socket has an associated channel then the resulting output stream delegates all of its operations to the channel. If the channel is in non-blocking mode then the output stream's write operations will throw an java.nio.channels.IllegalBlockingModeException.

Closing the returned OutputStream will close the associated socket.

Returns:
an output stream for writing bytes to this socket.
Throws:
java.io.IOException if an I/O error occurs when creating the output stream or if the socket is not connected.
Revised:
1.4
Spec:
JSR-51
 
     public OutputStream getOutputStream() throws IOException {
         if (isClosed())
             throw new SocketException("Socket is closed");
         if (!isConnected())
             throw new SocketException("Socket is not connected");
         if (isOutputShutdown())
             throw new SocketException("Socket output is shutdown");
         final Socket s = this;
         OutputStream os = null;
         try {
             os = (OutputStream)
                 AccessController.doPrivileged(new PrivilegedExceptionAction() {
                     public Object run() throws IOException {
                         return .getOutputStream();
                     }
                 });
         } catch (java.security.PrivilegedActionException e) {
             throw (IOExceptione.getException();
         }
         return os;
     }

    
Enable/disable TCP_NODELAY (disable/enable Nagle's algorithm).

Parameters:
on true to enable TCP_NODELAY, false to disable.
Throws:
SocketException if there is an error in the underlying protocol, such as a TCP error.
Since:
JDK1.1
See also:
getTcpNoDelay()
 
     public void setTcpNoDelay(boolean onthrows SocketException {
         if (isClosed())
             throw new SocketException("Socket is closed");
         getImpl().setOption(., Boolean.valueOf(on));
     }

    
Tests if TCP_NODELAY is enabled.

Returns:
a boolean indicating whether or not TCP_NODELAY is enabled.
Throws:
SocketException if there is an error in the underlying protocol, such as a TCP error.
Since:
JDK1.1
See also:
setTcpNoDelay(boolean)
 
     public boolean getTcpNoDelay() throws SocketException {
         if (isClosed())
             throw new SocketException("Socket is closed");
         return ((BooleangetImpl().getOption(.)).booleanValue();
     }

    
Enable/disable SO_LINGER with the specified linger time in seconds. The maximum timeout value is platform specific. The setting only affects socket close.

Parameters:
on whether or not to linger on.
linger how long to linger for, if on is true.
Throws:
SocketException if there is an error in the underlying protocol, such as a TCP error.
java.lang.IllegalArgumentException if the linger value is negative.
Since:
JDK1.1
See also:
getSoLinger()
 
     public void setSoLinger(boolean onint lingerthrows SocketException {
         if (isClosed())
             throw new SocketException("Socket is closed");
         if (!on) {
             getImpl().setOption(.new Boolean(on));
         } else {
             if (linger < 0) {
                 throw new IllegalArgumentException("invalid value for SO_LINGER");
             }
             if (linger > 65535)
                 linger = 65535;
             getImpl().setOption(.new Integer(linger));
         }
     }

    
Returns setting for SO_LINGER. -1 returns implies that the option is disabled. The setting only affects socket close.

Returns:
the setting for SO_LINGER.
Throws:
SocketException if there is an error in the underlying protocol, such as a TCP error.
Since:
JDK1.1
See also:
setSoLinger(boolean,int)
 
     public int getSoLinger() throws SocketException {
         if (isClosed())
             throw new SocketException("Socket is closed");
         Object o = getImpl().getOption(.);
         if (o instanceof Integer) {
             return ((Integero).intValue();
         } else {
             return -1;
         }
     }

    
Send one byte of urgent data on the socket. The byte to be sent is the lowest eight bits of the data parameter. The urgent byte is sent after any preceding writes to the socket OutputStream and before any future writes to the OutputStream.

Parameters:
data The byte of data to send
Throws:
java.io.IOException if there is an error sending the data.
Since:
1.4
 
     public void sendUrgentData (int datathrows IOException  {
         if (!getImpl().supportsUrgentData ()) {
             throw new SocketException ("Urgent data not supported");
         }
         getImpl().sendUrgentData (data);
     }

    
Enable/disable OOBINLINE (receipt of TCP urgent data) By default, this option is disabled and TCP urgent data received on a socket is silently discarded. If the user wishes to receive urgent data, then this option must be enabled. When enabled, urgent data is received inline with normal data.

Note, only limited support is provided for handling incoming urgent data. In particular, no notification of incoming urgent data is provided and there is no capability to distinguish between normal data and urgent data unless provided by a higher level protocol.

Parameters:
on true to enable OOBINLINE, false to disable.
Throws:
SocketException if there is an error in the underlying protocol, such as a TCP error.
Since:
1.4
See also:
getOOBInline()
 
     public void setOOBInline(boolean onthrows SocketException {
         if (isClosed())
             throw new SocketException("Socket is closed");
         getImpl().setOption(., Boolean.valueOf(on));
     }

    
Tests if OOBINLINE is enabled.

Returns:
a boolean indicating whether or not OOBINLINE is enabled.
Throws:
SocketException if there is an error in the underlying protocol, such as a TCP error.
Since:
1.4
See also:
setOOBInline(boolean)
 
     public boolean getOOBInline() throws SocketException {
         if (isClosed())
             throw new SocketException("Socket is closed");
         return ((BooleangetImpl().getOption(.)).booleanValue();
     }

    
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.

Parameters:
timeout the specified timeout, in milliseconds.
Throws:
SocketException if there is an error in the underlying protocol, such as a TCP error.
Since:
JDK 1.1
See also:
getSoTimeout()
    public synchronized void setSoTimeout(int timeoutthrows SocketException {
        if (isClosed())
            throw new SocketException("Socket is closed");
        if (timeout < 0)
          throw new IllegalArgumentException("timeout can't be negative");
        getImpl().setOption(.new Integer(timeout));
    }

    
Returns setting for SO_TIMEOUT. 0 returns implies that the option is disabled (i.e., timeout of infinity).

Returns:
the setting for SO_TIMEOUT
Throws:
SocketException if there is an error in the underlying protocol, such as a TCP error.
Since:
JDK1.1
See also:
setSoTimeout(int)
    public synchronized int getSoTimeout() throws SocketException {
        if (isClosed())
            throw new SocketException("Socket is closed");
        /* extra type safety */
        if (o instanceof Integer) {
            return ((Integero).intValue();
        } else {
            return 0;
        }
    }

    
Sets the SO_SNDBUF option to the specified value for this Socket. The SO_SNDBUF option is used by the platform's networking code as a hint for the size to set the underlying network I/O buffers.

Because SO_SNDBUF is a hint, applications that want to verify what size the buffers were set to should call getSendBufferSize().

Parameters:
size the size to which to set the send buffer size. This value must be greater than 0.
Throws:
SocketException if there is an error in the underlying protocol, such as a TCP error.
java.lang.IllegalArgumentException if the value is 0 or is negative.
Since:
1.2
See also:
getSendBufferSize()
    public synchronized void setSendBufferSize(int size)
    throws SocketException{
        if (!(size > 0)) {
            throw new IllegalArgumentException("negative send size");
        }
        if (isClosed())
            throw new SocketException("Socket is closed");
        getImpl().setOption(.new Integer(size));
    }

    
Get value of the SO_SNDBUF option for this Socket, that is the buffer size used by the platform for output on this Socket.

Returns:
the value of the SO_SNDBUF option for this Socket.
Throws:
SocketException if there is an error in the underlying protocol, such as a TCP error.
Since:
1.2
See also:
setSendBufferSize(int)
    public synchronized int getSendBufferSize() throws SocketException {
        if (isClosed())
            throw new SocketException("Socket is closed");
        int result = 0;
        if (o instanceof Integer) {
            result = ((Integer)o).intValue();
        }
        return result;
    }

    
Sets the SO_RCVBUF option to the specified value for this Socket. The SO_RCVBUF option is used by the platform's networking code as a hint for the size to set the underlying network I/O buffers.

Increasing the receive buffer size can increase the performance of network I/O for high-volume connection, while decreasing it can help reduce the backlog of incoming data.

Because SO_RCVBUF is a hint, applications that want to verify what size the buffers were set to should call getReceiveBufferSize().

The value of SO_RCVBUF is also used to set the TCP receive window that is advertized to the remote peer. Generally, the window size can be modified at any time when a socket is connected. However, if a receive window larger than 64K is required then this must be requested before the socket is connected to the remote peer. There are two cases to be aware of:

  1. For sockets accepted from a ServerSocket, this must be done by calling ServerSocket.setReceiveBufferSize(int) before the ServerSocket is bound to a local address.

  2. For client sockets, setReceiveBufferSize() must be called before connecting the socket to its remote peer.

Parameters:
size the size to which to set the receive buffer size. This value must be greater than 0.
Throws:
java.lang.IllegalArgumentException if the value is 0 or is negative.
SocketException if there is an error in the underlying protocol, such as a TCP error.
Since:
1.2
See also:
getReceiveBufferSize()
ServerSocket.setReceiveBufferSize(int)
    public synchronized void setReceiveBufferSize(int size)
    throws SocketException{
        if (size <= 0) {
            throw new IllegalArgumentException("invalid receive size");
        }
        if (isClosed())
            throw new SocketException("Socket is closed");
        getImpl().setOption(.new Integer(size));
    }

    
Gets the value of the SO_RCVBUF option for this Socket, that is the buffer size used by the platform for input on this Socket.

Returns:
the value of the SO_RCVBUF option for this Socket.
Throws:
SocketException if there is an error in the underlying protocol, such as a TCP error.
Since:
1.2
See also:
setReceiveBufferSize(int)
    public synchronized int getReceiveBufferSize()
    throws SocketException{
        if (isClosed())
            throw new SocketException("Socket is closed");
        int result = 0;
        if (o instanceof Integer) {
            result = ((Integer)o).intValue();
        }
        return result;
    }

    
Enable/disable SO_KEEPALIVE.

Parameters:
on whether or not to have socket keep alive turned on.
Throws:
SocketException if there is an error in the underlying protocol, such as a TCP error.
Since:
1.3
See also:
getKeepAlive()
    public void setKeepAlive(boolean onthrows SocketException {
        if (isClosed())
            throw new SocketException("Socket is closed");
        getImpl().setOption(., Boolean.valueOf(on));
    }

    
Tests if SO_KEEPALIVE is enabled.

Returns:
a boolean indicating whether or not SO_KEEPALIVE is enabled.
Throws:
SocketException if there is an error in the underlying protocol, such as a TCP error.
Since:
1.3
See also:
setKeepAlive(boolean)
    public boolean getKeepAlive() throws SocketException {
        if (isClosed())
            throw new SocketException("Socket is closed");
    }

    
Sets traffic class or type-of-service octet in the IP header for packets sent from this Socket. As the underlying network implementation may ignore this value applications should consider it a hint.

The tc must be in the range 0 <= tc <= 255 or an IllegalArgumentException will be thrown.

Notes:

For Internet Protocol v4 the value consists of an octet with precedence and TOS fields as detailed in RFC 1349. The TOS field is bitset created by bitwise-or'ing values such the following :-

  • IPTOS_LOWCOST (0x02)
  • IPTOS_RELIABILITY (0x04)
  • IPTOS_THROUGHPUT (0x08)
  • IPTOS_LOWDELAY (0x10)
The last low order bit is always ignored as this corresponds to the MBZ (must be zero) bit.

Setting bits in the precedence field may result in a SocketException indicating that the operation is not permitted.

As RFC 1122 section 4.2.4.2 indicates, a compliant TCP implementation should, but is not required to, let application change the TOS field during the lifetime of a connection. So whether the type-of-service field can be changed after the TCP connection has been established depends on the implementation in the underlying platform. Applications should not assume that they can change the TOS field after the connection.

For Internet Protocol v6 tc is the value that would be placed into the sin6_flowinfo field of the IP header.

Parameters:
tc an int value for the bitset.
Throws:
SocketException if there is an error setting the traffic class or type-of-service
Since:
1.4
See also:
getTrafficClass()
    public void setTrafficClass(int tcthrows SocketException {
        if (tc < 0 || tc > 255)
            throw new IllegalArgumentException("tc is not in range 0 -- 255");
        if (isClosed())
            throw new SocketException("Socket is closed");
        getImpl().setOption(.new Integer(tc));
    }

    
Gets traffic class or type-of-service in the IP header for packets sent from this Socket

As the underlying network implementation may ignore the traffic class or type-of-service set using setTrafficClass(int) this method may return a different value than was previously set using the setTrafficClass(int) method on this Socket.

Returns:
the traffic class or type-of-service already set
Throws:
SocketException if there is an error obtaining the traffic class or type-of-service value.
Since:
1.4
See also:
setTrafficClass(int)
    public int getTrafficClass() throws SocketException {
        return ((Integer) (getImpl().getOption(.))).intValue();
    }

    
Enable/disable the SO_REUSEADDR socket option.

When a TCP connection is closed the connection may remain in a timeout state for a period of time after the connection is closed (typically known as the TIME_WAIT state or 2MSL wait state). For applications using a well known socket address or port it may not be possible to bind a socket to the required SocketAddress if there is a connection in the timeout state involving the socket address or port.

Enabling SO_REUSEADDR prior to binding the socket using bind(java.net.SocketAddress) allows the socket to be bound even though a previous connection is in a timeout state.

When a Socket is created the initial setting of SO_REUSEADDR is disabled.

The behaviour when SO_REUSEADDR is enabled or disabled after a socket is bound (See isBound()) is not defined.

Parameters:
on whether to enable or disable the socket option
Throws:
SocketException if an error occurs enabling or disabling the SO_RESUEADDR socket option, or the socket is closed.
Since:
1.4
See also:
getReuseAddress()
bind(java.net.SocketAddress)
isClosed()
isBound()
    public void setReuseAddress(boolean onthrows SocketException {
        if (isClosed())
            throw new SocketException("Socket is closed");
        getImpl().setOption(., Boolean.valueOf(on));
    }

    
Tests if SO_REUSEADDR is enabled.

Returns:
a boolean indicating whether or not SO_REUSEADDR is enabled.
Throws:
SocketException if there is an error in the underlying protocol, such as a TCP error.
Since:
1.4
See also:
setReuseAddress(boolean)
    public boolean getReuseAddress() throws SocketException {
        if (isClosed())
            throw new SocketException("Socket is closed");
    }

    
Closes this socket.

Any thread currently blocked in an I/O operation upon this socket will throw a SocketException.

Once a socket has been closed, it is not available for further networking use (i.e. can't be reconnected or rebound). A new socket needs to be created.

Closing this socket will also close the socket's InputStream and OutputStream.

If this socket has an associated channel then the channel is closed as well.

Throws:
java.io.IOException if an I/O error occurs when closing this socket.
See also:
isClosed()
Revised:
1.4
Spec:
JSR-51
    public synchronized void close() throws IOException {
        synchronized() {
            if (isClosed())
                return;
            if ()
                .close();
             = true;
        }
    }

    
Places the input stream for this socket at "end of stream". Any data sent to the input stream side of the socket is acknowledged and then silently discarded.

If you read from a socket input stream after invoking shutdownInput() on the socket, the stream will return EOF.

Throws:
java.io.IOException if an I/O error occurs when shutting down this socket.
Since:
1.3
See also:
shutdownOutput()
close()
setSoLinger(boolean,int)
isInputShutdown()
    public void shutdownInput() throws IOException
    {
        if (isClosed())
            throw new SocketException("Socket is closed");
        if (!isConnected())
            throw new SocketException("Socket is not connected");
        if (isInputShutdown())
            throw new SocketException("Socket input is already shutdown");
        getImpl().shutdownInput();
         = true;
    }

    
Disables the output stream for this socket. For a TCP socket, any previously written data will be sent followed by TCP's normal connection termination sequence. If you write to a socket output stream after invoking shutdownOutput() on the socket, the stream will throw an IOException.

Throws:
java.io.IOException if an I/O error occurs when shutting down this socket.
Since:
1.3
See also:
shutdownInput()
close()
setSoLinger(boolean,int)
isOutputShutdown()
    public void shutdownOutput() throws IOException
    {
        if (isClosed())
            throw new SocketException("Socket is closed");
        if (!isConnected())
            throw new SocketException("Socket is not connected");
        if (isOutputShutdown())
            throw new SocketException("Socket output is already shutdown");
        getImpl().shutdownOutput();
         = true;
    }

    
Converts this socket to a String.

Returns:
a string representation of this socket.
    public String toString() {
        try {
            if (isConnected())
                return "Socket[addr=" + getImpl().getInetAddress() +
                    ",port=" + getImpl().getPort() +
                    ",localport=" + getImpl().getLocalPort() + "]";
        } catch (SocketException e) {
        }
        return "Socket[unconnected]";
    }

    
Returns the connection state of the socket.

Returns:
true if the socket successfuly connected to a server
Since:
1.4
    public boolean isConnected() {
        // Before 1.3 Sockets were always connected during creation
        return  || ;
    }

    
Returns the binding state of the socket.

Returns:
true if the socket successfuly bound to an address
Since:
1.4
See also:
bind(java.net.SocketAddress)
    public boolean isBound() {
        // Before 1.3 Sockets were always bound during creation
        return  || ;
    }

    
Returns the closed state of the socket.

Returns:
true if the socket has been closed
Since:
1.4
See also:
close()
    public boolean isClosed() {
        synchronized() {
            return ;
        }
    }

    
Returns whether the read-half of the socket connection is closed.

Returns:
true if the input of the socket has been shutdown
Since:
1.4
See also:
shutdownInput()
    public boolean isInputShutdown() {
        return ;
    }

    
Returns whether the write-half of the socket connection is closed.

Returns:
true if the output of the socket has been shutdown
Since:
1.4
See also:
shutdownOutput()
    public boolean isOutputShutdown() {
        return ;
    }

    
The factory for all client sockets.
    private static SocketImplFactory factory = null;

    
Sets the client socket implementation factory for the application. The factory can be specified only once.

When an application creates a new client socket, the socket implementation factory's createSocketImpl method is called to create the actual socket implementation.

Passing null to the method is a no-op unless the factory was already set.

If there is a security manager, this method first calls the security manager's checkSetFactory method to ensure the operation is allowed. This could result in a SecurityException.

Parameters:
fac the desired factory.
Throws:
java.io.IOException if an I/O error occurs when setting the socket factory.
SocketException if the factory is already defined.
java.lang.SecurityException if a security manager exists and its checkSetFactory method doesn't allow the operation.
See also:
SocketImplFactory.createSocketImpl()
java.lang.SecurityManager.checkSetFactory()
    public static synchronized void setSocketImplFactory(SocketImplFactory fac)
        throws IOException
    {
        if ( != null) {
            throw new SocketException("factory already defined");
        }
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkSetFactory();
        }
         = fac;
    }

    
Sets performance preferences for this socket.

Sockets use the TCP/IP protocol by default. Some implementations may offer alternative protocols which have different performance characteristics than TCP/IP. This method allows the application to express its own preferences as to how these tradeoffs should be made when the implementation chooses from the available protocols.

Performance preferences are described by three integers whose values indicate the relative importance of short connection time, low latency, and high bandwidth. The absolute values of the integers are irrelevant; in order to choose a protocol the values are simply compared, with larger values indicating stronger preferences. Negative values represent a lower priority than positive values. If the application prefers short connection time over both low latency and high bandwidth, for example, then it could invoke this method with the values (1, 0, 0). If the application prefers high bandwidth above low latency, and low latency above short connection time, then it could invoke this method with the values (0, 1, 2).

Invoking this method after this socket has been connected will have no effect.

Parameters:
connectionTime An int expressing the relative importance of a short connection time
latency An int expressing the relative importance of low latency
bandwidth An int expressing the relative importance of high bandwidth
Since:
1.5
    public void setPerformancePreferences(int connectionTime,
                                          int latency,
                                          int bandwidth)
    {
        /* Not implemented yet */
    }
New to GrepCode? Check out our FAQ X