Java socket programming Basics

Source: Internet
Author: User

This article Excerpted from: http://www.builder.com.cn/2008/0414/813590.shtml


What is socket )?

Network API is typically used to communicate with other programs based on TCP/IP network Java programs. Network API relies on socket for communication.

The socket can be seen as an endpoint in the communication connection between two programs. One program writes a piece of information into the socket, and the socket sends this information to the other socket.

Let's analyze 1. program a on host a writes a piece of information into the socket, and the content of the socket is accessed by the network management software of host, the information is sent to host B through the network interface card of host a. The network interface card of host B receives the information and sends it to the network management software of host B, the Network Management Software saves this information in the socket of host B, and then program B can read this information in the socket.

Each host in a TCP/IP network is assigned a uniqueIP addressThe IP address is a 32-bit unsigned integer. Because it is not converted to binary, it is usually separated by decimal places, for example, 198.163.227.6. As you can see, the IP address is composed of four parts, the range of each part is 0-255, which indicates an 8-bit address.

Every TCP/IP-based network communication program is assigned a uniquePort and port numberThe port is an information buffer to retain the input/output information in the socket. The port number is a 16-bit unsigned integer in the range of 0-65535, to differentiate every program on the host (the port number is like the room number in the House ),Less than 256 of short slogans are retained to standard applicationsFor example, the POP3 port number is 110, and each socket is combined into an IP address, port, and port number. In this way, each socket t can be differentiated as a whole.

Java Socket class

When the client program needs to communicate with the server program, the client program creates a socket object on the client. Two common constructor functions are socket (inetaddress ADDR, int port) and socket (string host, int port ). For the first inetaddress subclass object, use the ADDR parameter to obtain the IP address of the server host. For the secondThe host parameter package of the function is allocated to the inetaddress object.If no IP address is consistent with the host parameter, the unknownhostexception object is thrown. Both functions obtain the server port number through the port parameter. Suppose a connection has been established,The Network API binds the IP address of the client program and any port number in the socket-based stream socket of the client.Otherwise, both functions will throw an ioexception object.

If a socket object is created, it may be obtained from the service program by calling the getinputstream () method of the socket.Input stream read transmitted informationOr you can call the getoutputstream () method of the socketSend messages from an outbound stream. After the reading and writing activity is complete, the client program calls the close () method to close the stream and stream socket. The following Code creates a socket object with the host address of the service program as 198.163.227.6 and port number as 13, then, read the input stream from the newly created socket object, and then close the stream and socket object.

Socket s = new Socket ("198.163.227.6", 13);InputStream is = s.getInputStream ();// Read from the stream.is.close ();s.close ();

Java instance:

// SSClient.javaimport java.io.*;import java.net.*;class SSClient{ public static void main (String [] args) {    String host = "localhost";    // If user specifies a command-line argument, that argument    // represents the host name.    if (args.length == 1) host = args [0];    BufferedReader br = null;    PrintWriter pw = null;    Socket s = null;    try{      // Create a socket that attempts to connect to the server      // program on the host at port 10000.      s = new Socket (host, 10000);      // Create an input stream reader that chains to the socket's      // byte-oriented input stream. The input stream reade      // converts bytes read from the socket to characters. The      // conversion is based on the platform's default character      // set.      InputStreamReader isr;      isr = new InputStreamReader (s.getInputStream ());      // Create a buffered reader that chains to the input stream      // reader. The buffered reader supplies a convenient method // for reading entire lines of text.      br = new BufferedReader (isr);      // Create a print writer that chains to the socket's byte-      // oriented output stream. The print writer creates an      // intermediate output stream writer that converts      // characters sent to the socket to bytes. The conversion      // is based on the platform's default character set.      pw = new PrintWriter (s.getOutputStream (), true);      // Send the DATE command to the server.      pw.println ("DATE");      // Obtain and print the current date/time.      System.out.println (br.readLine ());      // Send the PAUSE command to the server. This allows several      // clients to start and verifies that the server is spawning      // multiple threads. pw.println ("PAUSE");      // Send the DOW command to the server.      pw.println ("DOW");      // Obtain and print the current day of week.      System.out.println (br.readLine ());      // Send the DOM command to the server.       pw.println ("DOM");      // Obtain and print the current day of month.      System.out.println (br.readLine ());      // Send the DOY command to the server.      pw.println ("DOY");      // Obtain and print the current day of year.      System.out.println (br.readLine ());    }    catch (IOException e)    {      // Exception process...     }    finally    {      try{        if (br != null) br.close ();        if (pw != null) pw.close ();        if (s != null) s.close ();      }      catch (IOException e){       // Exception process...       }    }  }}

Ssclient creates a socket object to contact the service program running on port 10000 of the host. the IP address of the host is determined by the host variable.

Ssclient will obtain the input and output streams of the socket. It is very easy to read and write the strings around the input stream of bufferedreader and the output stream of printwriter, the ssclient service programs issue various date/time commands and get a response. Each response is printed. Once the last response is printed, the finally substring of the try/catch/Finally structure will be executed, the finally substring will close bufferedreader before closing the socket.
And printwriter.

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.