Java Reference
In-Depth Information
Q: Do I just make up a port number?
A: Sure. A port number can be any 16-bit integer (between 0 and
65,535). However, you should use only port numbers larger than
1,024 because the lower ports are reserved for common protocols
such as HTTP, FTP, Telnet, and others. Often, a port number needs
to be assigned to you by a network administrator. However, if I am
just testing applications or writing program for a small network, I
just pick large numbers. Ports greater than 10,000 seem to be
pretty safe because many common applications such as Web
servers use ports up into the 9,000 range.
Q: What if I pick a port number that is already being used?
A: You will get an exception in your Java program. In that case, I
would handle the exception and try another port until you are
successful. In most methods that require a port number, you can
pass in 0 and let the JVM find a port for you.
I am now ready to show you how to do some network programming, so let's
start with creating a TCP connection using sockets.
Using Sockets
If TCP is similar to placing a telephone call, a socket is the telephone. Sockets
provide the communication mechanism between two computers using TCP. A
client program creates a socket on its end of the communication and attempts
to connect that socket to a server. When the connection is made, the server cre-
ates a socket object on its end of the communication. The client and server can
now communicate by writing to and reading from the socket.
The java.net package contains classes that provide all of the low-level com-
munication for you. For example, the java.net.Socket class represents a socket,
and the java.net.ServerSocket class provides a mechanism for the server pro-
gram to listen for clients and establish connections with them.
The following steps occur when establishing a TCP connection between two
computers using sockets:
1.
The server instantiates a ServerSocket object, denoting which port num-
ber communication is to occur on.
2.
The server invokes the accept() method of the ServerSocket class. This
method waits until a client connects to the server on the given port.
Search WWH ::




Custom Search