Java Reference
In-Depth Information
Socket Class
The java.net.Socket class represents the socket that both the client and server
use to communicate with each other. The client obtains a Socket object by
instantiating one, whereas the server obtains a Socket object from the return
value of the accept() method. The Socket class has five constructors that a
client uses to connect to a server:
public Socket(String host, int port) throws UnknownHostException,
IOException. Attempts to connect to the specified server at the speci-
fied port. If this constructor does not throw an exception, the connection
is successful and the client is connected to the server. This is the simplest
constructor to use when connecting to a server.
public Socket(InetAddress host, int port) throws IOException. Identical
to the previous constructor, except that the host is denoted by an InetAd-
dress object.
public Socket(String host, int port, InetAddress localAddress, int local-
Port) throws IOException. Connects to the specified host and port,
creating a socket on the local host at the specified address and port. This
is useful for clients who have multiple IP addresses or who want the
socket to bind on a specific local port.
public Socket(InetAddress host, int port, InetAddress localAddress, int
localPort) throws IOException. Identical to the previous constructor,
except that the host is denoted by an InetAddress object instead of a
String.
public Socket(). Creates an unconnected socket. Use the connect()
method to connect this socket to a server.
When the Socket constructor returns, it does not simply instantiate a Socket
object. Within the constructor, it actually attempts to connect to the specified
server and port. If the constructor returns successfully, the client has a TCP
connection to the server!
Some methods of interest in the Socket class are listed here. Notice that both
the client and server have a Socket object, so these methods can be invoked by
both the client and server.
public void connect(SocketAddress host, int timeout) throws IOExcep-
tion. Connects the socket to the specified host. This method is needed
only when you instantiated the Socket using the no-argument constructor.
public InetAddress getInetAddress(). Returns the address of the other
computer that this socket is connected to.
Search WWH ::




Custom Search