Java Reference
In-Depth Information
The following are the basic steps involved in TCP socket communication:
1. Create an instance of a socket class.
2. Send serialized messages using the socket I/O streams.
3. Close the socket connection.
Note For the initial connection there are two requirements: a socket client that sends the initial connec-
tion request and a socket server that is listening for incoming connection requests. But once the connection
has been set up, you have a connection between two sockets, and either one can send or receive data. It is
up to the communication protocol to determine which socket is sending data and which socket is receiving
data at any given time. We will cover application protocols in the section “The Application Protocol” later in
this chapter. As you might imagine, if either client or server does not follow the application protocol, the
point-to-point communication will break down.
TCP Socket Clients
The class java.net.Socket is responsible for implementing a socket-to-socket connection.
The constructor for this class, which actually attempts to connect to the destination
machine, requires both the hostname as a URL (as a string) and the port of the destination
machine. Table 7-1 lists the various public constructors for java.net.Socket .
Table 7-1. Public Constructors for java.net.Socket
Socket Class
Socket Class Constructors
public Socket()
Creates an unconnected socket.
public Socket(InetAddress address,
The most commonly used. Creates a connected
int port)
socket to the supplied address and port.
public Socket(InetAddress address,
Creates a socket that connects to the remote
int port, InetAddress localAddr,
address and port and also binds to the local
int localPort)
address and port.
public Socket(String host,
Creates a stream socket and connects it to the
int port)
specified host and port.
public Socket(String host,
Connects to a remote host and port and binds to
int port, InetAddress localAddr,
the local address and port.
int localPort)
Once a socket connection is made, you can obtain information about the connection
through a variety of getter methods. The client-side socket is not bound to the port number
the server is residing on. Rather, the client-side socket is assigned a local port it uses to com-
municate with the server.
Search WWH ::




Custom Search