Java Network Programming
Network programming refers to writing programs that run on multiple devices (computers), which are connected to each other through a network.
The java.net package contains the J2SE API with classes and interfaces that provide low-level communication details. You can use these classes and interfaces directly to focus on solving problems without worrying about communication details.
The java.net package provides support for two common network protocols:
-
TCP: TCP (Transmission Control Protocol) is a connection-oriented, reliable, byte-stream-based transport layer communication protocol. The TCP layer is an intermediate layer above the IP layer and below the application layer. TCP guarantees reliable communication between two applications. It is commonly used in Internet protocols and is called TCP/IP.
-
UDP: UDP (User Datagram Protocol) is located in the transport layer of the OSI model. It is a connectionless protocol that provides datagrams to be sent between applications. Because UDP lacks reliability and is a connectionless protocol, applications usually must tolerate some lost, erroneous, or duplicated packets.
This tutorial mainly explains the following two topics.
-
Socket programming: This is the most widely used network concept and has been explained in great detail.
-
URL handling: This part will be covered in a separate section; click here to learn more about URL handling in the Java language.
Socket programming
Sockets use TCP to provide a communication mechanism between two computers. A client program creates a socket and attempts to connect to the server's socket.
When the connection is established, the server creates a Socket object. The client and server can now communicate by writing to and reading from the Socket object.
The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for server programs to listen for clients and establish connections with them.
The following steps occur when establishing a TCP connection between two computers using sockets:
-
The server instantiates a ServerSocket object, representing communication through a port on the server.
-
The server calls the accept() method of the ServerSocket class, which will wait until a client connects to the given port on the server.
-
While the server is waiting, a client instantiates a Socket object, specifying the server name and port number to request a connection.
-
The Socket class constructor attempts to connect the client to the specified server and port number. If communication is established, a Socket object is created on the client side that can communicate with the server.
-
On the server side, the accept() method returns a new socket reference on the server, which is connected to the client's socket.
After the connection is established, communication occurs through I/O streams. Each socket has an output stream and an input stream; the client's output stream is connected to the server's input stream, and the client's input stream is connected to the server's output stream.
TCP is a bidirectional communication protocol, so data can be sent through two data streams at the same time. The following are a complete set of useful methods provided by some classes to implement sockets.
Methods of the ServerSocket class
A server application uses the java.net.ServerSocket class to acquire a port and listen for client requests.
The ServerSocket class has four constructors:
| No. | Method Description |
|---|---|
| 1 | public ServerSocket(int port) throws IOException |
| Creates a server socket bound to a specific port. | |
| 2 | public ServerSocket(int port, int backlog) throws IOException |
| Creates a server socket with the specified backlog and binds it to the specified local port number. | |
| 3 | public ServerSocket(int port, int backlog, InetAddress address) throws IOException |
| Creates a server using the specified port, listen backlog, and local IP address to bind to. | |
| 4 | public ServerSocket() throws IOException |
| Creates an unbound server socket. |
Creates an unbound server socket. If the ServerSocket constructor does not throw an exception, it means your application has successfully bound to the specified port and is listening for client requests.
Here are some common methods of the ServerSocket class:
| No. | Method Description |
|---|---|
| 1 | public int getLocalPort() |
| Returns the port on which this socket is listening. | |
| 2 | public Socket accept() throws IOException |
| Listens for and accepts a connection to this socket. | |
| 3 | public void setSoTimeout(int timeout) |
| Enables/disables SO_TIMEOUT with the specified timeout value, in milliseconds. | |
| 4 | public void bind(SocketAddress host, int backlog) |
| Binds the ServerSocket to a specific address (IP address and port number). |
Methods of the Socket class
The java.net.Socket class represents the socket used by both client and server to communicate with each other. The client obtains a Socket object by instantiating it, while the server obtains a Socket object through the return value of the accept() method.
The Socket class has five constructors.
| No. | Method Description |
|---|---|
| 1 | public Socket(String host, int port) throws UnknownHostException, IOException. |
| Creates a stream socket and connects it to the specified port number on the specified host. | |
| 2 | public Socket(InetAddress host, int port) throws IOException |
| Creates a stream socket and connects it to the specified port number at the specified IP address. | |
| 3 | public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException. |
| Creates a socket and connects it to the specified remote port on the specified remote host. | |
| 4 | public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException. |
| Creates a socket and connects it to the specified remote port at the specified remote address. | |
| 5 | public Socket() |
| Creates an unconnected socket through the system-default type of SocketImpl |
When the Socket constructor returns, it does not merely instantiate a Socket object; it actually attempts to connect to the specified server and port.
The following are some methods of interest; note that both the client and the server have a Socket object, so either the client or the server can call these methods.
| No. | Method Description |
|---|---|
| 1 | public void connect(SocketAddress host, int timeout) throws IOException |
| Connects this socket to the server with a specified timeout value. | |
| 2 | public InetAddress getInetAddress() |
| Returns the address to which the socket is connected. | |
| 3 | public int getPort() |
| Returns the remote port to which this socket is connected. | |
| 4 | public int getLocalPort() |
| Returns the local port to which this socket is bound. | |
| 5 | public SocketAddress getRemoteSocketAddress() |
| Returns the address of the endpoint to which this socket is connected, or null if not connected. | |
| 6 | public InputStream getInputStream() throws IOException |
| Returns this socket's input stream. | |
| 7 | public OutputStream getOutputStream() throws IOException |
| Returns this socket's output stream. | |
| 8 | public void close() throws IOException |
| Closes this socket. |
Methods of the InetAddress class
This class represents an Internet Protocol (IP) address. The following are useful methods when doing socket programming:
| No. | Method Description |
|---|---|
| 1 | static InetAddress getByAddress(byte[] addr) |
| Returns an InetAddress object given the raw IP address. | |
| 2 | static InetAddress getByAddress(String host, byte[] addr) |
| Creates an InetAddress from the provided host name and IP address. | |
| 3 | static InetAddress getByName(String host) |
| Determines the IP address of the host given the host name. | |
| 4 | **String getHostAddress() ** |
| Returns the IP address string (in textual representation). | |
| 5 | **String getHostName() ** |
| Gets the host name of this IP address. | |
| 6 | static InetAddress getLocalHost() |
| Returns the local host. | |
| 7 | String toString() |
| Converts this IP address to a String. |
Socket client example
The following GreetingClient is a client program that connects to the server via a socket, sends a request, and then waits for a response.
GreetingClient.java file code:
//
File name: GreetingClient.java
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
{
System
.
out
.
println
(
"
Connecting to host:
"
serverName
"
, port number:
"
port
)
;
Socket
client
=
new
Socket
(
serverName
,
port
)
;
System
.
out
.
println
(
"
Remote host address:
"
client
.
getRemoteSocketAddress
(
)
)
;
OutputStream
outToServer
=
client
.
getOutputStream
(
)
;
DataOutputStream
out
=
new
DataOutputStream
(
outToServer
)
;
out
.
writeUTF
(
"
Hello from
"
client
.
getLocalSocketAddress
(
)
)
;
InputStream
inFromServer
=
client
.
getInputStream
(
)
;
DataInputStream
in
=
new
DataInputStream
(
inFromServer
)
;
System
.
out
.
println
(
"
Server response:
"
in
.
readUTF
(
)
)
;
client
.
close
(
)
;
}
catch
(
IOException
e
)
{
e
.
printStackTrace
(
)
;
}
}
}
Socket server example
The following GreetingServer program is a server-side application that uses a Socket to listen on a specified port.
GreetingServer.java file code:
//
File name: GreetingServer.java
import
java
.
net
.*;
import
java
.
io
.*;
public
class
GreetingServer
extends
Thread
{
private
ServerSocket
serverSocket
;
public
GreetingServer
(
int
port
)
throws
IOException
{
serverSocket
=
new
ServerSocket
(
port
)
;
serverSocket
.
setSoTimeout
(
10000
)
;
}
public
void
run
(
)
{
while
(
true
)
{
try
{
System
.
out
.
println
(
"
Waiting for remote connection on port:
"
serverSocket
.
getLocalPort
(
)
"
...
"
)
;
Socket
server
=
serverSocket
.
accept
(
)
;
System
.
out
.
println
(
"
Remote host address:
"
server
.
getRemoteSocketAddress
(
)
)
;
DataInputStream
in
=
new
DataInputStream
(
server
.
getInputStream
(
)
)
;
System
.
out
.
println
(
in
.
readUTF
(
)
)
;
DataOutputStream
out
=
new
DataOutputStream
(
server
.
getOutputStream
(
)
)
;
out
.
writeUTF
(
"
Thanks for connecting to me:
"
server
.
getLocalSocketAddress
(
)
"
\n
Goodbye!
"
)
;
server
.
close
(
)
;
}
catch
(
SocketTimeoutException
s
)
{
System
.
out
.
println
(
"
Socket timed out!
"
)
;
break
;
}
catch
(
IOException
e
)
{
e
.
printStackTrace
(
)
;
break
;
}
}
}
public
static
void
main
(
String
[
]
args
)
{
int
port
=
Integer
.
parseInt
(
args
[
0
]
)
;
try
{
Thread
t
=
new
GreetingServer
(
port
)
;
t
.
run
(
)
;
}
catch
(
IOException
e
)
{
e
.
printStackTrace
(
)
;
}
}
}
Compile the above two java files and execute the following command to start the service using port number 6066:
$ javac GreetingServer.java
$ java GreetingServer 6066
等待远程连接,端口号为:6066...
Open a new command window and execute the above command to start the client:
$ javac GreetingClient.java
$ java GreetingClient localhost 6066
连接到主机:localhost ,端口号:6066
远程主机地址:localhost/127.0.0.1:6066
服务器响应: 谢谢连接我:/127.0.0.1:6066
Goodbye!