Network programming refers to writing programs that run on multiple devices (computers). These devices are connected through the network.
The J2SE API in the java.net package contains classes and interfaces that provide low-level communication details. You can use these classes and interfaces directly to focus on problem solving without focusing on communication details.
The java.net package provides support for two common network protocols:
- TCP : TCP is an abbreviation for Transmission Control Protocol, which guarantees reliable communication between two applications. Usually used for Internet protocols, it is called TCP / IP.
- UDP : UDP is an abbreviation for User Datagram Protocol, a connectionless protocol. Provides packets of data to be sent between applications.
This tutorial focuses on the following two topics.
- Socket programming : This is the most widely used network concept and it has been explained in great detail.
- URL processing : This section will be covered in other pages. 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. The client program creates a socket and tries to connect to the server's socket.
When the connection is established, the server creates a Socket object. Clients and servers can now communicate by writing and reading Socket objects.
The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for server programs to listen to clients and establish connections with them.
The following steps occur when using a socket to establish a TCP connection between two computers:
- The server instantiates a ServerSocket object that communicates through the port on the server.
- The server calls the accept() method of the ServerSocket class, which will wait until the 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 the connection.
- The constructor of the Socket class attempts to connect the client to the specified server and port number. If communication is established, creating a Socket object on the client 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, the I/O stream is used to communicate. 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 two-way communication protocol, so data can be sent at the same time through two data streams. Here is a complete set of useful methods provided by some classes to implement sockets.
ServerSocket method
The server application uses the java.net.ServerSocket class to get a port and listens 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 using 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 with the specified port, listening backlog, and the local IP address to bind to. |
| 4 | Public ServerSocket() throws IOException Creates 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 listens 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 connections to this socket. |
| 3 | Public void setSoTimeout(int timeout) Enables/disables SO_TIMEOUT by specifying a timeout value in milliseconds. |
| 4 | Public void bind(SocketAddress host, int backlog) Binds the ServerSocket to a specific address (IP address and port number). |
Socket method
The java.net.Socket class represents sockets that both clients and servers use to communicate with each other. The client obtains a Socket object through instantiation, and the server obtains a Socket object via 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. Create a stream socket and connect 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 for 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 on the specified remote address. |
| 5 | Public Socket() creates an unconnected socket through the system default type SocketImpl |
When the Socket constructor returns, there is no simple instantiation of a Socket object. It actually tries to connect to the specified server and port.
The following is a list of interesting methods. Note that both the client and the server have a Socket object, so both the client and 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 and specifies a timeout value. |
| 2 | Public InetAddress getInetAddress() Returns the address of the socket connection. |
| 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 this socket is connected to, or null if it is not connected. |
| 6 | Public InputStream getInputStream() throws IOException Returns the input stream for this socket. |
| 7 | Public OutputStream getOutputStream() throws IOException Returns the output stream of this socket. |
| 8 | Public void close() throws IOException Close this socket. |
InetAddress method
This class represents the Internet Protocol (IP) address. The following is a list of useful methods for programming Socket:
| No. | Method description |
| 1 | Static InetAddress getByAddress(byte[] addr) Returns the InetAddress object given the original IP address. |
| 2 | Static InetAddress getByAddress(String host, byte[] addr) Creates an InetAddress based on the supplied host name and IP address. |
| 3 | Static InetAddress getByName(String host) Determines the host's IP address given the host name. |
| 4 | String getHostAddress() Returns an IP address string in textual form. |
| 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 instance
The following GreetingClient is a client program that connects to the server through a socket and 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("connected to the host:" + serverName + " ,the 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 instance
The following GreetingServer program is a server-side application that uses Socket to listen to a specific 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 a 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("Thank you for connecting me: " + 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 file codes and execute the following command to start the service using port number 6066:
$ javac GreetingServer.java $ java GreetingServer 6066 waiting for a remote connection, port number: 6066...
Open a new command window and execute the above command to open the client:
$ javac GreetingClient . java $ java GreetingClient localhost 6066 Connect to host: localhost, port number: 6066 Remote host address: localhost/127.0.0.1:6066 Server Response: Thanks for connecting me: /127.0.0.1:6066 Goodbye!
Comments
Post a Comment