java USES the Socket class to receive and send data

  • 2020-05-10 18:19:04
  • OfStack

Network applications are divided into two parts: the client side and the server side, and the Socket class is the Java class responsible for handling the client side communication. This class allows you to connect to a server that specifies an IP or domain name, and to send and receive data to and from the server. The use of the Socket class will be discussed in detail in this article and subsequent articles, including the basics of the Socket class, the various ways to connect, the get and set methods, timeouts during connections, and closing network connections.

In this article, we will discuss the basic steps and methods for using the Socket class. The following three steps are required for a network client to connect to a server.

Connect to server Send and receive data Shut down network connection

Connect to the server

On the client side, there are two ways to connect to the server. One is to connect to the server via IP, and the other is to connect to the server via domain name.

So these two ways are essentially one way. In the underlying client by IP to connect to the server, but there is 1 set of difference between these two approaches, if IP way to connect to the server program, the client simply according to connect IP, if through the domain name to connect to the server, the client must through DNS DNS into IP, then according to this IP to connect.

In many programming languages or development tools (such as C/C++, Delphi), when using a domain name to connect to a server, you must first resolve the domain name to IP and then connect via IP. In Java, the domain name resolution function is already included in the Socket class. Therefore, we only need to use the domain name as IP1.

The most common way to connect to a server program through the Socket class is to pass IP or the domain name and port number into the Socket class through the constructor of the Socket class. The constructor of the Socket class has many overloaded forms, and in this section we will discuss only one of the most common: public Socket (String host, int port). From the definition of this constructor, you simply pass IP or the domain name and port number directly into the constructor. The following code is an example of a program that connects to a server-side program:


package mysocket; 
import java.net.*; 
public class MyConnection
{
  public static void main(String[] args)
  {
    try
    {
      if (args.length > 0)
      {
        Socket socket = new Socket(args[0], 80);
        System.out.println(args[0] + " Connected successfully !");
      }
      else
        System.out.println(" Please specify IP Or domain name! ");
    }
    catch (Exception e)
    {
      System.err.println(" Error message: " + e.getMessage());
    }
  }
}

In the above example, IP or domain name is passed into the program via the command line argument and then connected via Socket socket = new Socket(args[0], 80) to port 80 of IP or domain name specified by the command line argument. Because the constructor of the Socket class USES throws when it is defined, try must be used when calling the constructor of the Socket class... The catch statement is used to catch errors, or the throws statement is used to throw errors on the main function.

Connecting to the server using the Socket class allows you to determine which ports are open on a host. The code below is a program that scans the device for which ports are opened.

2. Send and receive data

The two most important methods in the Socket class are getInputStream and getOutputStream. These two methods are used to obtain InputStream and OutputStream objects for reading and writing data, respectively. Here, InputStream reads the data that the server program sends to the client, while OutputStream is the data that the client sends to the server program.

When writing the actual network client program, whether to use getInputStream or getOutputStream, and who to use first and who to use later depends on the specific application. Such as through the connection of posts and telecommunications press website (www. ptpress. com. cn) port 80 (1) for HTTP protocol used by the default port, and sends a string, and then read from www. ptpress. com. cn return information.


package mysocket;
import java.net.*;
import java.io.*; 
public class MyConnection2
{
  public static void main(String[] args) throws Exception
  {
    Socket socket = new Socket("www.ptpress.com.cn", 80);
    //  Sends data to the server application 
    OutputStream ops = socket.getOutputStream();    
    OutputStreamWriter opsw = new OutputStreamWriter(ops);
    BufferedWriter bw = new BufferedWriter(opsw);
     
    bw.write("hello world\r\n\r\n");
    bw.flush();
     
    //  Receive data from the server application 
    InputStream ips = socket.getInputStream();
    InputStreamReader ipsr = new InputStreamReader(ips);
    BufferedReader br = new BufferedReader(ipsr);
    String s = "";    
    while((s = br.readLine()) != null)
      System.out.println(s);    
    socket.close();
  }
}

Here are two things to keep in mind when writing the above code:

1. In order to improve the efficiency of data transmission, Socket class does not transmit data after calling write method every time, but writes the data to be transmitted into a buffer (8192 bytes by default), and then sends the data in this buffer out through flush method. Therefore, bw.flush (); It's a must.

2. When sending a string, add "\r\n\r\n" after Hello World, this is because the head of the HTTP protocol is "\r\ r\n" as the closing mark (the details of the HTTP protocol will be explained later). Therefore, by adding "\r\n\r\n" after sending the string, You can make the server program think that the HTTP header is finished and ready to process. If you do not add "\r\n\r\n", then the server program will wait 1 until the end of the HTTP header, i.e. "\r\n\r\n". If this is the case, the server program will not send the response to the client, and br.readLine () will be blocked on the response information surface because it cannot be read until the connection times out.

3. Turn off your Internet connection

By now, we have a basic understanding of how to use the Socket class, but after the Socket class has processed the data, the most reasonable closure is to close the network connection using the close method of the Socket class. Although the close method has been used in this article, there is more than just the close method to shut down a network connection. Let's take a look at the circumstances under which Java can shut down a network connection.

There are four situations that can cause a network connection to shut down:

  directly calls the close methods of the Socket class. As long as one of the InputStream and OutputStream of the Socket class is shut down, the network connection is automatically shut down (the network connection must be shut down by calling InputStream and OutputStream's close methods). The network connection closes automatically when the program exits. Setting the Socket object to null or not closing the most used new Socket(...) After the new object is created, the network connection is automatically closed after the memory space allocated to the Socket object is collected by the garbage collector of JVM.    

Although all four of these methods can achieve the same goal, it is best for a robust network application to shut down the network using either method 1 or 2. This is because methods 3 and 4 1 do not normally shut down the network connection immediately, and if so, some applications will be left with a large number of unwanted network connections, which can consume large amounts of system resources.

After the Socket object is closed, we can determine whether an Socket object is closed by using the isClosed method. However, using the isClosed method returns only the current state of the Socket object, that is, isClosde returns true as long as it is closed, regardless of whether the Socket object has ever been connected successfully. If you just create an unconnected Socket object, isClose also returns true. The following code will output false.


Socket socket = new Socket();
System.out.println(socket.isClosed());

In addition to the isClose method, the Socket class has an isConnected method to determine whether the Socket object is connected successfully. The name may mislead the reader. In fact, what isConnected method judges is not the current connection state of Socket object, but whether Socket object has been successfully connected. If it has been successfully connected, isClose will return true even if isClose returns true, isConnected will still return true. Therefore, to determine whether the current Socket object is in the connected state, both isClose and isConnected methods must be used, that is, the Socket object is only in the connected state when isClose returns false and isConnected returns true. The following code demonstrates the various states of the Socket object described above.


package mysocket;
import java.net.*; 
public class MyCloseConnection
{
  public static void printState(Socket socket, String name)
  {
    System.out.println(name + ".isClosed():" + socket.isClosed());
    System.out.println(name + ".isConnected():" + socket.isConnected());
    if (socket.isClosed() == false && socket.isConnected() == true)
      System.out.println(name + " In the connected state !");
    else
      System.out.println(name + " It's in the disconnected state !");
    System.out.println();
  }
  public static void main(String[] args) throws Exception
  {
    Socket socket1 = null, socket2 = null;
 
    socket1 = new Socket("www.ptpress.com.cn", 80);
    printState(socket1, "socket1");
 
    socket1.getOutputStream().close();
    printState(socket1, "socket1");
 
    socket2 = new Socket();
    printState(socket2, "socket2");
 
    socket2.close();
    printState(socket2, "socket2");
  }
}

After running the above code, you will get the following output:

socket1.isClosed():false
socket1.isConnected():true
socket1 is connected!
socket1.isClosed():true
socket1.isConnected():true
socket1 is not connected!
socket2.isClosed():false
socket2.isConnected():false
socket2 is not connected!
socket2.isClosed():true
socket2.isConnected():false
socket2 is not connected!

As you can see from the output, after OutputStream of socket1 was turned off, socket1 also turned off automatically. As can be seen from the above code, for an Socket object socket2 that is not connected to the server, its isClosed method is false, and true must be explicitly called using socket2.close in order for socket2's isClosed method to return true.

While most of the time it is possible to shut down the network connection directly using the Socket class or the close method of the I/o stream, sometimes we only want to close OutputStream or InputStream, and not close the network connection while shutting down the I/o stream. This requires the use of two other methods of the Socket class: shutdownInput and shutdownOutput, which only turn off the corresponding input and output streams, but do not have the ability to turn off the network connection at the same time. Like isClosed and isConnected methods 1, Socket class also provides two methods to determine whether the input and output streams of Socket objects are closed. The two methods are isInputShutdown() and isOutputShutdown(). The following code demonstrates the process of closing only the input and output streams:


package mysocket;
import java.net.*; 
public class MyCloseConnection1
{
  public static void printState(Socket socket)
  {
    System.out.println("isInputShutdown:" + socket.isInputShutdown());
    System.out.println("isOutputShutdown:" + socket.isOutputShutdown());
    System.out.println("isClosed:" + socket.isClosed());
    System.out.println();
  }
  public static void main(String[] args) throws Exception
  {
    Socket socket = new Socket("www.ptpress.com.cn", 80);
    printState(socket);
    socket.shutdownInput();
    printState(socket);
    socket.shutdownOutput();
    printState(socket);
  }
}

After running the above generation, you will get the following output:

isInputShutdown:false
isOutputShutdown:false
isClosed:false
isInputShutdown:true
isOutputShutdown:false
isClosed:false
isInputShutdown:true
isOutputShutdown:true
isClosed:false

As you can see from the output, isClosed method 1 directly returns false, so you can be sure that shutdownInput and shutdownOutput do not affect the state of the Socket object.

I hope this article has been helpful to you, and that's where java USES the Socket class to receive and send data. We hope you continue to pay attention to our website! Stay tuned to learn about java.


Related articles: