English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Network programming refers to writing programs that run on multiple devices (computers) that are connected to each other through a network.
java.net package contains J2SE's API contains classes and interfaces that provide low-level communication details. You can directly use these classes and interfaces to focus on solving problems without concerning yourself with communication details.
java.net package provides support for two common network protocols:
TCPTCP (Transmission Control Protocol) is a connection-oriented, reliable, byte-stream-based transport layer communication protocol. The TCP layer is the intermediate layer above the IP layer and below the application layer. TCP ensures reliable communication between two applications. It is commonly used in Internet protocols and is known as TCP. / IP.
UDPUDP (User Datagram Protocol) is a connectionless protocol located in the transport layer of the OSI model. It provides datagrams for data to be sent between applications. Due to the lack of reliability and the nature of being a connectionless protocol, applications usually must allow for some lost, erroneous, or duplicate packets.
This tutorial mainly explains the following two topics.
Socket ProgrammingThis is the most widely used network concept, which has been explained in great detail.
URL HandlingThis part will be discussed in another section. Click here for more detailed information on URL Handling in Java Language.
Sockets use TCP to provide a communication mechanism between two computers. The 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 and reading to 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 using sockets to establish a TCP connection between two computers:
The server instantiates a ServerSocket object to represent communication through the port on the server.
The server calls the accept() method of the ServerSocket class, which will wait indefinitely until the client connects to the port given on the server.
While the server is waiting, a client instantiates a Socket object, specifying the server name and port to request a connection.
The constructor of the Socket class attempts to connect the client to the specified server and port. 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, use I/In the O stream communication, 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 set of complete and useful methods provided by the class to implement sockets.
The server application uses the java.net.ServerSocket class to obtain a port and listen for client requests.
The ServerSocket class has four constructors:
Serial Number | Method Description |
1 | public ServerSocket(int port) throws IOException Create a server socket bound to a specific port. |
2 | public ServerSocket(int port, int backlog) throws IOException Create a server socket with the specified backlog and bind it to the specified local port. |
3 | public ServerSocket(int port, int backlog, InetAddress address) throws IOException Create a server by specifying the port, listen backlog, and local IP address to bind to. |
4 | public ServerSocket() throws IOException Create an unbound server socket. |
Create an unbound server socket. If the ServerSocket constructor does not throw an exception, it means that your application has successfully bound to the specified port and is listening for client requests.
Here are some commonly used methods of the ServerSocket class:
Serial Number | Method Description |
1 | public int getLocalPort() Return the port on which this socket is listening. |
2 | public Socket accept() throws IOException Listen and accept connections to this socket. |
3 | public void setSoTimeout(int timeout) Enable through specifying the timeout value/Disable SO_TIMEOUT in milliseconds. |
4 | public void bind(SocketAddress host, int backlog) Bind the ServerSocket to a specific address (IP address and port). |
The java.net.Socket class represents the socket used by both clients and servers for mutual communication. The client obtains a Socket object by instantiation, while the server gets a Socket object through the return value of the accept() method.
The Socket class has five constructors.
Serial Number | Method Description |
1 | public Socket(String host, int port) throws UnknownHostException, IOException. Create a stream socket and connect it to the specified port on the specified host. |
2 | public Socket(InetAddress host, int port) throws IOException Create a stream socket and connect it to the specified port on the specified IP address. |
3 | public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException. Create a socket and connect 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 on the specified remote address. |
5 | public Socket() Creates an unconnected socket through the system default type of SocketImpl |
When the Socket constructor returns, and no simple example is created, it actually tries to connect to the specified server and port.
The following methods of interest are listed, note that both the client and server have a Socket object, so either the client or server can call these methods.
Serial Number | Method Description |
1 | public void connect(SocketAddress host, int timeout) throws IOException Connects this socket to a server and specifies a timeout value. |
2 | public InetAddress getInetAddress() Returns the address of the socket connection. |
3 | public int getPort() Returns the remote port this socket is connected to. |
4 | public int getLocalPort() Returns the local port this socket is bound to. |
5 | public SocketAddress getRemoteSocketAddress() Returns the address of the endpoint connected to this socket, or null if not connected. |
6 | public InputStream getInputStream() throws IOException Returns the input stream of this socket. |
7 | public OutputStream getOutputStream() throws IOException Returns the output stream of this socket. |
8 | public void close() throws IOException Closes this socket. |
This class represents an Internet Protocol (IP) address. The following methods are listed that are useful during socket programming:
Serial Number | Method Description |
1 | static InetAddress getByAddress(byte[] addr) Returns an InetAddress object given the original IP address. |
2 | static InetAddress getByAddress(String host, byte[] addr) Creates an InetAddress based on the provided hostname and IP address. |
3 | static InetAddress getByName(String host) Determines the IP address of the host given a hostname. |
4 | String getHostAddress() Returns the IP address string (in text form). |
5 | String getHostName() Gets the hostname of the IP address. |
6 | static InetAddress getLocalHost() Returns the local host. |
7 | String toString() Convert this IP address to String. |
The following GreetingClient is a client program that connects to the server via socket, sends a request, and then waits for a response.
// 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("Connected 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(); } } }
The following GreetingServer program is a server-side application that uses Socket to listen on a specified port.
// 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, port number:") + 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("谢谢连接我:" + server.getLocalSocketAddress() + "\nGoodbye!"); 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: 6066:
$ javac GreetingServer.java $ java GreetingServer 6066 Waiting for a remote connection, port:6066...
Open a new command window and execute the following commands to start the client:
$ javac GreetingClient.java $ java GreetingClient localhost 6066 Connecting to host: localhost, port:6066 Remote Host Address: localhost/127.0.0.1:6066 Server Response: Thank you for connecting to me:/127.0.0.1:6066 Goodbye!