Java Reference
In-Depth Information
public int getPort().
Returns the port the socket is bound to on the
remote machine.
public int getLocalPort().
Returns the port the socket is bound to on the
local machine.
public SocketAddress getRemoteSocketAddress().
Returns the address
of the remote socket.
public InputStream getInputStream() throws IOException. Returns the
input stream of the socket. The input stream is connected to the output
stream of the remote socket.
public OutputStream getOutputStream() throws IOException. Returns
the output stream of the socket. The output stream is connected to the
input stream of the remote socket.
public void close() throws IOException. Closes the socket, which makes
this Socket object no longer capable of connecting again to any server.
The Socket class contains many more methods, so check the documentation
for a complete list. You will notice that many of the methods in the Socket class
involve accessing and changing the various TCP properties of a connection,
such as a time-out value or keep-alive setting. Of all the methods in Socket,
probably the two most important ones are getInputStream() and getOutput-
Stream(), which I will now discuss in detail.
Communicating between Sockets
The InputStream and OutputStream attributes of a Socket are the ways the two
computers communicate with each other. For example, if the server wants to
send data to the client, the server needs to write to the OutputStream of its
socket, which is then read by the InputStream of the client's socket. Similarly,
data can be sent from the client to the server using the client's OutputStream
and the server's InputStream.
The following GreetingClient is a client program that connects to a server by
using a socket and sends a greeting, and then waits for a response. Study the
program and try to determine exactly how the client accomplishes this.
import java.net.*;
import java.io.*;
public class GreetingClient
{
public static void main(String [] args)
{
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try
{
Search WWH ::




Custom Search