Java uses the socket class to receive and send data _java

Source: Internet
Author: User
Tags flush readline

The network application is divided into two parts: the client and the service side, while the socket class is the Java class responsible for handling client communication. This class enables you to connect to a server with a specified IP or domain name, and can send and receive data to and from the server. The use of the socket class is discussed in detail in this article and later in the article, including the base of the socket class, various modes of connection, get and set methods, timeouts during the connection, and shutting down the network connection.

In this article, we'll discuss the basic steps and methods for using the socket class. The General network client program does the following three steps when connecting to a service program.

    1. Connecting to a server
    2. Sending and receiving data
    3. Turn off network connections

First, connect the server

There are two ways for the client to connect to the server, one is to connect the server by IP, and the other is to connect the server through the domain name.

In fact, both of these approaches are essentially a way of looking at them. At the bottom of the client is through IP to connect the server, but the two ways there is a certain difference, if the IP way to connect the service-side program, the client is simply based on IP connection, if the domain name to connect the server, the client must be DNS to resolve the domain name into IP, Then the connection is based on this IP.

In many programming languages or development tools (such as C + +, Delphi) using domain name way to connect to the server, you must first resolve the domain name to IP, and then through the IP connection, and in Java has been the domain name resolution function in the socket class, therefore, We only need to use the same domain name as IP.

The most common way to connect server programs through the socket class is through the constructor of the socket class to pass the IP or domain name and the port number as parameters into the socket class. The constructor for the Socket class has many overloaded forms, and in this section only one of the most commonly used forms is discussed: Public Socket (String host, int port). From the definition of this constructor, you simply pass the IP or domain name and the port number directly to the constructor. The following code is an example program that connects 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);
        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, the IP or domain name is passed in to the program through the command-line arguments, then the 80 port of the IP or domain name specified by the command-line argument is connected via the socket socket = new socket (args[0], 80). Because the constructor of the socket class uses throws when it is defined, you must use the Try...catch statement to catch the error when calling the constructor of the socket class, or you can use the throws statement on the main function to throw the error.

Connect to a server using the socket class to determine which ports are open for a single host. The following code is a program that scans which ports are opened on this computer.

Second, send and receive data

The two most important methods in the socket class are getInputStream and Getoutputstream. The two methods are used to get the InputStream and OutputStream objects for reading and writing data, respectively. Here the InputStream reads the data that the server program sends over to the client, and OutputStream is the data that the client sends to the service-side program.

When writing the actual network client program, use the getInputStream, or use the Getoutputstream, and first use who to use after the specific application decision. such as by connecting to the posts and Telecommunications publishing house website (www.ptpress.com.cn) of port 80 (typically the default port used by the HTTP protocol), and send a string, and finally read the information returned from the www.ptpress.com.cn.

Package mysocket;
Import java.net.*;
Import java.io.*; 
public class MyConnection2
{public
  static void Main (string[] args) throws Exception
  {
    socket socket = NE W Socket ("www.ptpress.com.cn",);
    Sending data to a server-side program
    outputstream OPS = Socket.getoutputstream ();    
    OutputStreamWriter OPSW = new OutputStreamWriter (OPS);
    BufferedWriter bw = new BufferedWriter (OPSW);
     
    Bw.write ("Hello world\r\n\r\n");
    Bw.flush ();
     
    receiving data from a server-side program
    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 ();
  }

Note the following two points when writing the above code:

1. In order to improve the efficiency of data transfer, the socket class does not transmit data after each call to the Write method, but instead writes the transmission to a buffer (8,192 bytes by default), and then sends the data in the buffer through the flush method, so Bw.flush (); is necessary.

2. Add "\r\n\r\n" to the Hello World after sending the string because the HTTP protocol header is "\r\n\r\n" As the end sign (the details of the HTTP protocol will be explained later), so by adding "\r\n\r\n" after sending the string , you can make the server-side program think that the HTTP header is finished and can handle it. If you do not add "\r\n\r\n", then the server-side program will wait until the end of the HTTP header, that is, "\r\n\r\n." If so, the server-side program will not send a response message to the client, and Br.readline () will be blocked for unreadable response information until the connection times out.

Third, turn off the network connection

Up to now, we have a preliminary understanding of the basic use of the socket class, but after the socket class processing data, the most reasonable method is to use the Close method of the socket class to turn off the network connection. Although the Close method has already been used in, the way to turn the network connection off is not just the closing method, let's look at the circumstances in which Java can shut down the network connection.

There are 4 things that can cause a network connection to shut down:

    1. Call the Close method of the socket class directly.
    2. As long as the InputStream and outputstream of the socket class have one shutdown, the network connection shuts down automatically (you must turn off the stream by calling the Close method of InputStream and OutputStream to make the network cute and close automatically).
    3. The network connection shuts down automatically when the program exits.
    4. Set the socket object to null or closed with the most new socket (...) When a new object is created, the network connection is automatically turned off after the JVM's garbage collector reclaims the memory space allocated for the socket object.

Although these 4 methods can achieve the same goal, a robust network program is best to turn off network connections using either the 1th or 2nd method. This is because the 3rd and 4th methods generally do not turn off the network connection immediately, and if so, for some applications, there will be a legacy of unwanted network connections that can consume a significant amount of system resources.

After the socket object is closed, we can use the IsClosed method to determine whether a socket object is turned off. However, using the IsClosed method returns only the current state of the socket object, that is, the ISCLOSDE returns true, regardless of whether the socket object has been successfully connected, as long as it is closed. Isclose also returns true if only an disconnected socket object is established. The following code will output false.

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

In addition to the Isclose method, the socket class also has a isconnected method to determine whether the socket object is connected successfully. To see this name, perhaps the reader will have misunderstood. In fact, isconnected method is not judged by the current connection state of the socket object, but whether the socket object has been successfully connected, if the successful connection, even now Isclose return true,isconnected still return true. Therefore, to determine whether the current socket object is connected, you must use both the Isclose and isconnected methods, that is, the socket object is connected only if Isclose returns True false,isconnected return. The following code illustrates the process of producing 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 + "Connected!");
    else
      System.out.println (name + "is not connected!");
    System.out.println ();
  }
  public static void Main (string[] args) throws Exception
  {
    Socket socket1 = null, Socket2 = NULL;
 
    Socket1 = new Socket ("www.ptpress.com.cn");
    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 have the following output:

Socket1.isclosed (): false
Socket1.isconnected (): True
Socket1 is in a connected state!
Socket1.isclosed (): True
Socket1.isconnected (): True
Socket1 is not in a connected state!
Socket2.isclosed (): false
Socket2.isconnected (): false
Socket2 is not in a connected state!
Socket2.isclosed (): True
Socket2.isconnected (): false
Socket2 is not in a connected state!

From the output, it can be seen that after the Socket1 OutputStream closed, the SOCKET1 also automatically closed. And in the code above we can see that for a socket object that is not connected to the server Socket2, its isclosed method is false, and to let Socket2 isclosed method return True, The Close method must be called using the Socket2.close display.

While most of the time you can turn off network connections directly using the socket class or the Close method of the input/output stream, sometimes we just want to turn off OutputStream or InputStream, while shutting down the input output stream does not turn off the network connection. This requires two other ways to use the Socket class: Shutdowninput and Shutdownoutput, which only close the corresponding input and output streams, and they do not turn off the network connection at the same time. As with isclosed and isconnected methods, the socket class also provides two methods to determine whether the socket object's input or output stream is closed, both Isinputshutdown () and Isoutputshutdown (). The following code shows the process of turning off the input and output streams only:

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 you run the previous 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, the IsClosed method always returns false, so you can be sure that shutdowninput and shutdownoutput do not affect the state of the socket object.

I hope this article will help you, Java use the socket class to receive and send data content is introduced here. I hope you will continue to pay attention to our website! Want to learn Java can continue to focus on this site.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.