Java network programming socket programming etc

  • 2020-07-21 07:36:36
  • OfStack

Network programming refers to writing programs that run on multiple devices (computers) that are connected over a network.

API of J2SE in the ES4en.net package contains 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, short for Transmission Control Protocol, ensures reliable communication between two applications. Commonly used for Internet protocols, known as TCP/IP.

UDP:UDP is short 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 is covered in a separate section. Click here to learn more about URL processing in the Java language.

Socket programming

Sockets use TCP to provide a mechanism for communication between two computers. The client program creates a socket and attempts to connect to the server's socket.

When a connection is established, the server creates an Socket object. The client and server can now communicate by writing and reading Socket objects.

The java.net.Socket class represents a socket, and the ES56en.net.ServerSocket class provides a mechanism for server programs to listen to clients and establish connections with them.

The following steps occur when using sockets to establish an TCP connection between two computers:

The server instantiates an ServerSocket object to communicate over a port on the server.

The server calls the accept () method of the ServerSocket class, which waits until the client connects to the given port on the server.

While the server is waiting, a client instantiates an Socket object, specifying the server name and port number to request a connection.

The constructor of the Socket class attempts to connect the client to the specified server and port number. If communication is established, an Socket object is created on the client side to communicate with the server.

On the server side, the accept() method returns a new socket reference on the server that is connected to the client's socket.

Once the connection is established, communication is made using the I/O stream. Each socket has an output stream and an input stream. The output from the client side flows into the input stream from the server side, and the input from the client side flows into the output stream from the server side.

TCP is a two-way communication protocol so that data can be sent through two data streams at the same time.

Methods of the ServerSocket class

The server application gets a port by using the ES106en.net.ServerSocket class and listens for client requests.

The ServerSocket class has four constructors:

序号 方法描述
1

 public ServerSocket(int port) throws IOException

创建绑定到特定端口的服务器套接字

2

 public ServerSocket(int port, int backlog) throws IOException

利用指定的 backlog 创建服务器套接字并将其绑定到指定的本地端口号

3

public ServerSocket(int port, int backlog, InetAddress address) throws IOException

使用指定的端口、侦听 backlog 和要绑定到的本地 IP 地址创建服务器

4

public ServerSocket() throws IOException

创建非绑定服务器套接字

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 common methods of the ServerSocket class:

序号  方法描述
1

 public int getLocalPort()

返回此套接字在其上侦听的端口

2

public Socket accept() throws IOException

侦听并接受到此套接字的连接

3

public void setSoTimeout(int timeout)

通过指定超时值启用/禁用 SO_TIMEOUT,以毫秒为单位

4

public void bind(SocketAddress host, int backlog)

将 ServerSocket 绑定到特定地址(IP 地址和端口号)

Methods of the Socket class

The ES130en.net.ES132en class represents the sockets that both clients and servers use to communicate with each other. The client gets an Socket object by instantiation, and the server gets an Socket object by the return value of the accept() method.

The Socket class has five constructors.

序号  方法描述
1

public Socket(String host, int port) throws UnknownHostException, IOException.

创建1个流套接字并将其连接到指定主机上的指定端口号

2

public Socket(InetAddress host, int port) throws IOException

创建1个流套接字并将其连接到指定 IP 地址的指定端口号

3

public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException.

创建1个套接字并将其连接到指定远程主机上的指定远程端口

4

public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException

创建1个套接字并将其连接到指定远程地址上的指定远程端口

5

public Socket()

通过系统默认类型的 SocketImpl 创建未连接套接字

When the Socket constructor returns, instead of simply instantiating an Socket object, it actually attempts to connect to the specified server and port.

The methods of interest are listed below. Note that both the client and the server have an Socket object, so both the client and the server can invoke these methods.

序号  方法描述
1

public void connect(SocketAddress host, int timeout) throws IOException

将此套接字连接到服务器,并指定1个超时值

2

 public InetAddress getInetAddress()

返回套接字连接的地址

3

 public int getPort()

返回此套接字连接到的远程端口

4

public int getLocalPort()

返回此套接字绑定到的本地端口

5

 public SocketAddress getRemoteSocketAddress()

 返回此套接字连接的端点的地址,如果未连接则返回 null

6

public InputStream getInputStream() throws IOException

返回此套接字的输入流

7

public OutputStream getOutputStream() throws IOException

返回此套接字的输出流

8

public void close() throws IOException

关闭此套接字

Methods of the InetAddress class

This class represents the Internet Protocol (IP) address. Here are some useful ways to program Socket:

序号 方法描述
1

static InetAddress getByAddress(byte[] addr)

在给定原始 IP 地址的情况下,返回 InetAddress 对象

2

static InetAddress getByAddress(String host, byte[] addr)

根据提供的主机名和 IP 地址创建 InetAddress

3

static InetAddress getByName(String host)

在给定主机名的情况下确定主机的 IP 地址

4

String getHostAddress()

返回 IP 地址字符串(以文本表现形式)

5

String getHostName() 

获取此 IP 地址的主机名

6

static InetAddress getLocalHost()

返回本地主机

7

 String toString()

将此 IP 地址转换为 String


Socket client instance

The following GreetingClient is a client program that connects to the server via socket and sends a request, then waits for a response.


//  The 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 " + 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 side instance

The GreetingServer program shown below is a server-side application that USES Socket to listen on a specified port.


//  The 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 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 java code above and execute the following command to start the service with port number 6066:


$ java GreetingServer 6066
Waiting for client on port 6066...

Open the client as follows:


$ 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!

I hope you found this article helpful


Related articles: