Latest web development tutorials

Java Network Programming

Network programming means to write run on multiple devices (computer) program, these devices are connected through a network.

java.net package in the J2SE API contains classes and interfaces that provide low-level communication details. You can use these classes and interfaces to focus on solving the problem, rather than focus on communication details.

java.net package provides support for two common network protocols:

  • TCP: TCP is the abbreviation for Transmission Control Protocol, which guarantees reliable communication between two applications. Commonly used for Internet protocol, called TCP / IP.
  • UDP: UDP is an abbreviation of User Datagram Protocol, a connectionless protocol. Providing the data packet to be transmitted between the application data.

This tutorial explains the following two topics.

  • Socket Programming: This is the most widely used network concept, it has been explained in great detail to
  • URL Processing: This chapter talked in another space, click here to learn more about the URL handling Java language .

Socket Programming

Sockets use TCP provides a communication mechanism between the two computers. Client program creates a socket and trying to connect to the server socket.

When the connection is established, the server will create a Socket object. Client and server can now write and to read the Socket object to communicate.

java.net.Socket class represents a socket, and provides a java.net.ServerSocket class to listen for client server program, and establish a mechanism to connect with them.

It occurs when the TCP connection using the following steps to establish a socket between two computers:

  • ServerSocket server instantiate an object that represents the communications port on the server.
  • ServerSocket class server calls accept () method, which will wait until a client connects to the server on a given port.
  • When the server is waiting for a client to instantiate a Socket object, specify the server name and port number to request a connection.
  • Socket class constructor tries to connect the client to the specified server and port number. If the communication is established, to create a Socket object client can communicate with the server.
  • On the server side, accept () method returns a new socket server reference to the socket connected to the client socket.

After the connection is established by using the I / O stream during communications. Each socket has an input and an output stream stream. Client input stream output stream to a server, the client's input stream to the server output stream.

TCP is a bidirectional communication protocol, so data can be sent through the two data streams at the same time. The following is a complete class provides several useful methods to achieve sockets.


ServerSocket class methods

Server applications by using java.net.ServerSocket class for a port and listens for client requests.

ServerSocket class has four constructors:

No. Method Description
1 public ServerSocket (int port) throws IOException
Create a binding to a specific port of the server socket.
2 public ServerSocket (int port, int backlog ) throws IOException
With the specified backlog Creates a server socket and binds it to the specified local port number.
3 public ServerSocket (int port, int backlog , InetAddress address) throws IOException
Using the specified port, listen backlog, and to bind to the local IP address of the server is created.
4 public ServerSocket () throws IOException
Creates an unbound server socket.

Creates an unbound server socket. If the ServerSocket constructor method does not throw an exception, it means that your application has been successfully bound to the specified port, and listens for client requests.

Here are some common methods ServerSocket class:

No. Method Description
1 public int getLocalPort ()
Returns the port on which this socket is listening.
2 public Socket accept () throws IOException
He listens and accepts this socket.
3 public void setSoTimeout (int timeout)
By specifying the timeout value to enable / disable SO_TIMEOUT, in milliseconds.
4 public void bind (SocketAddress host, int backlog)
Binds the ServerSocket to a specific address (IP address and port number).

Socket class methods

java.net.Socket class behalf of the client and server to communicate with each other in the socket. To obtain a client Socket object by instantiating and the server to get a Socket object is returned by value accept () method.

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 IP address of the specified port number.
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 ()
Create an unconnected socket, the system default type SocketImpl

When the Socket constructor returns, and not simply instantiate a Socket object, it will actually try to connect to the specified server and port.

Here are some methods of interest, pay attention to the client and the server has a Socket object, regardless of the client or the server can call these methods.

No. Method Description
1 public void connect (SocketAddress host, int timeout) throws IOException
This socket connection to the server, and specify a timeout value.
2 public InetAddress getInetAddress ()
The return address of the socket connection.
3 public int getPort ()
Returns this socket is connected to the remote port.
4 public int getLocalPort ()
Returns this socket is bound to a local port.
5 public SocketAddress getRemoteSocketAddress ()
The return address of the endpoint this socket is connected, if it is unconnected returns null.
6 public InputStream getInputStream () throws IOException
Returns an input stream for this socket.
7 public OutputStream getOutputStream () throws IOException
Returns an output stream for this socket.
8 public void close () throws IOException
Closes this socket.

InetAddress class method

This class represents an Internet Protocol (IP) address. Listed below are useful when Socket programming method:

No. Method Description
1 static InetAddress getByAddress (byte [] addr )
In the case given the raw IP address, return InetAddress object.
2 static InetAddress getByAddress (String host, byte [] addr)
According to create InetAddress host names and IP addresses supplied.
3 static InetAddress getByName (String host)
Determine the IP address of the host in the case of a given host name.
4 String getHostAddress ()
Returns the IP address string (textual presentation).
5 String getHostName ()
Gets the host name for 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 is connected through a socket to the server and send a request, then wait for a response.

// 文件名 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 " + serverName
                             + " on port " + port);
         Socket client = new Socket(serverName, port);
         System.out.println("Just connected to "
                      + 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 says " + 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 on a specified port.

// 文件名 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 client on port " +
            serverSocket.getLocalPort() + "...");
            Socket server = serverSocket.accept();
            System.out.println("Just connected to "
                  + 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 to "
              + 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.start();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

Compile the above java code, and execute the following command to start the service, use the port number is 6066:

$ java GreetingServer 6066
Waiting for client on port 6066...
Open something like the following clients:
$ java GreetingClient localhost 6066
Connecting to localhost on port 6066
Just connected to localhost/127.0.0.1:6066
Server says Thank you for connecting to /127.0.0.1:6066
Goodbye!