Java Learning Notes-12th chapter Introduction to Java Networking programming

Source: Internet
Author: User

12th. Getting Started with Java networking programming

  1. Java provides three main types of network functionality:

    (1) URL and urlconnection: The most advanced of the three categories, through the URL network resource expression, you can easily determine the location of the data on the network. Using the representation and establishment of the URL, the Java program can read directly into the data placed on the network, or transfer its own data to the other end of the network.

    (2) Socket: also known as "socket", used to describe IP addresses and ports (in the Internet, each host in the network has a unique IP address, and each host provides multiple services by providing several different ports). In a client/server network, when an application running in a client (such as a Web browser) needs to access a server on the network, the client is temporarily assigned a socket, and then it makes a request to the server through the server's socket. In short, the data in the network is sent and received through the socket, the socket is like a file handle (a unique sequence number when reading and writing files), the user can read and write the socket to complete the client and server communication.

    (3) Datagram: The lowest of the three major categories. Other methods of network data transmission are supposed to establish a secure and stable channel when the program executes, but when the data is transferred in datagram, the destination of the data is recorded in the packet, and then it is placed directly on the network for transmission. The system does not guarantee that the data will be delivered safely or when it can be delivered. In other words, datagram cannot guarantee the quality of delivery.

  2. Understanding Java Network Programming Fundamentals

    (1) Two key issues in network programming : How to pinpoint one or more hosts on your network, and how to reliably and Data transfer is efficient. In the TCP/IP network protocol, IP addresses can uniquely determine a single host on the Internet, while TCP provides a reliable data transfer mechanism.

    (2) TCP/IP protocol (Transmission Control Protocol/Internet Interconnect protocol   network communication protocols)

    TCP/IP protocol is transmission-protocol/ The abbreviation for Internet Protocol is the most basic protocol for the Internet and a communication protocol for communicating with computers connected to the Internet. It defines how electronic devices, such as computers, are connected to the Internet, and the standards for how data travels between them. The TCP/IP protocol consists of the Network Layer IP protocol and the TCP protocol of the Transport layer.

    Computer network communication is divided into seven layers, from bottom to top: physical layer, Data link layer, network layer, transport layer, Session layer, presentation layer, application layer. Different network protocols are available on each tier.

    TCP/IP uses client/server mode for communication, and communication is point-to-point, that is, communication is between two hosts in the network. The TCP protocol is a Transmission Control protocol that aggregates information or splits the file into smaller packets. These packets are routed over the network to the TCP layer at the receiving end, and the TCP layer on the receiving side restores the package to the original file. The IP protocol is an Internet protocol that handles the address portions of each package so that the packets can reach their destination correctly. The gateway computer on the network makes routing choices based on the address of the information. Even if a packet route from the same file may be different, it will eventually converge at the destination.

  3. TCP protocol and UDP Protocol (transport layer)

    (1) TCP protocol : Connection-oriented, reliable transmission. A connection must be established between the client and the server before communication can take place. Get a sequential, error-free stream of data. You can transfer large volumes of data and ensure that the server receives all the data sent by the client correctly.

    (2) UDP protocol : User Datagram Protocol (Subscriber Datagram Protocol), a non-connected, unreliable transmission protocol. It wraps the information into a datagram for transmission, and the datagram contains the full source address or destination address. There is no guarantee that the datagram will reach its destination, when it arrives at its destination, and the correctness of the content. The transfer data size is limited to 64KB.

  4. IP Address

    The InetAddress class is used in Java to describe the IP address. There is no public constructor for this class, but it provides three static methods to get the InetAddress object. respectively:

    inetaddress getlocalhost (): Returns the InetAddress object for a local host.

    inetaddress Getbyname (String host): returns the host name of the specified InetAddress object.

    inetaddress[] Getallbyname (): for a multiple IP address host, this method can be used to obtain an array of IP addresses.

    In addition, the InetAddress class provides the following methods:

    String gethostaddress (); returns the IP address string.

    String gethostname (); returns the host name.

    For example:

    public class inetaddresstest{

    public static void Main (string[] args) {

    InetAddress IA;

    ia = Inetaddress.getlocalhost (); Get the InetAddress object for the local host

    String localhostaddress = ia.gethostaddress (); Get the local host IP address

    String localhostname = Ia.gethostname ()//Get local hostname

    ia = Inetaddress.getbyname ("www.baidu.com"); Get the InetAddress object of Baidu Net host

    String bdhostaddress = ia.gethostaddress (); Get Baidu web host address

    String bdhostname = Ia.gethostname (); Get Baidu web host name

    }

    }

  5. Port

    A port is a means of providing more network resources on a single host. Only the IP address and port number can uniquely determine the process in network traffic. The port is marked with a port number and the port number is represented by an integer of 0~65535.

  6. Using URLs to access network resources

    (1) URL: Uniform Resource Locator (Uniform Resource Locator), a reference to an Internet resource. In most cases, a resource is represented as a file, such as an HTML document, an image file, or a sound fragment. Therefore, the URL can be understood as an Internet resource address. The general format is as follows:

    <PROTOCOL>://<HOSTNAME:PORT>/<PATH>/<FILE>

    protocol represents an Internet protocol that is commonly used for HTTP, FTP, SMTP, and so on. Hostname represents the Internet host name where the resource resides. The hostname and IP address are one by one corresponding, and the IP address can be obtained by the hostname by the DNS name. Port represents the port number, and each Internet protocol has its own port number. Path and file represent the pathname and filename of the resource, respectively.

    (2) Creating a URL object

    You can use the URL class to access Internet resources in Java. The URL class is constructed as follows:

    A. URL (string spec): creates a URL object using a string spec that represents a URL address. For example:

    URL url = new URL ("http://www.sina.com.cn");

    b. url (url baseurl,string relativeurl): use absolute address BaseURL to create a URL object with relative address Relativeurl. For example:

    URL BaseURL = new URL ("http://www.base.edu.cn");

    URL url = new URL (baseURL, "/library/library.htm");

    c. URL (String protocol,string hostname,int port,string fileName): Use Network Protocol protocol, hostname HostName, port number port, File name filename filename to create the URL object. For example:

    URL url = new URL ("http", "www.baidu.com", "N", "/library/library.htm");

    d. URL (String protocol,string hostname,string filename): creates a URL object using the Network Protocol protocol, host name hostName, file name filename. For example:

    URL url = new URL ("http", "www.baidu.com", "/library/library.htm");

    Note: The construction method of the URL class throws a non-runtime exception malformedurlexception, which the program needs to handle.

  7. Read content directly from a URL object

    After successfully establishing a URL object, you can call the OpenStream () method to read the content from the network resource. For example:

    public class openstreamtest{

    public static void Main (string[] args) {

    try{

    URL sina = new URL ("http://www.sina.com.cn/");

    DataInputStream dis = new DataInputStream (Sina.openstream ());

    String ReadLine;

    while ((ReadLine = Dis.readline ())!=null) {

    System.out.print (ReadLine);

    }

    Dis.close ();

    }catch (malformedurlexception me) {

    System.out.print ("malformedurlexception:" +me);

    }catch (IOException IoE) {

    System.out.print ("IOException:" +ioe);

    }

    }

}

8. Create a URL to connect and read content from

With the OpenStream () method of the URL class, data can only be read from network resources. If you want to read and write data at the same time, you must use the URLConnection class to establish a URL connection. When you make a connection to a URL object, you first generate the URLConnection object through the OpenConnection () method of the URL object. The URLConnection object represents a communication connection between a Java program and a URL object on a network. If the connection process fails, IOException will be generated. For example:

Public class urlconnectiontest{

public static void Main (string[] args) {

try{

URL baidu = new URL ("http://www.baidu.com/");

URLConnection conn = Baidu.openconnection ();

Creating a data input stream

DataInputStream dis = new DataInputStream (baidu.getinputstream);

String Inputline;

while ((Inputline = Dis.readline ())!=null) {

System.out.print (Inputline);

}

Dis.close ();

}catch (malformedurlexception me) {

System.out.print ("malformedurlexception:" +me);

}catch (IOException IoE) {

System.out.print ("IOException:" +ioe);

}

}

}

9. using the socket for network communication

When the application layer communicates data through the transport layer, the TCP or UDP protocol encounters a problem that simultaneously provides concurrent services for multiple application processes. Multiple TCP connections or multiple application processes may require data to be transmitted over the same port. To differentiate between different application processes or connections, the computer operating system provides an interface called a socket (socket) for applications interacting with the TCP/IP protocol. Each socket is determined by the IP Address, Transport layer Protocol (TCP or UDP), port number three parameters alone.

When using the socket for server/client communication, there are three steps: Server listening, client request, connection acknowledgement.

(1) Server monitoring: The server-side socket in real-time monitoring a port for connection requests.

(2) Client request: refers to the client's socket to make a connection request, to connect to the target is the server-side socket. The client socket first needs to describe the server-side socket it wants to connect to, indicate the IP address and port number of the server-side socket, and then send the connection request to the server side.

(3) connection confirmation: when the socket on the server side hears or receives a connection request from the client socket, it responds to the client's request, establishes a new thread, and sends a description of the server-side socket to the client. Once the client confirms this description, a connection is built up. The server-side socket continues to be listening and receives connection requests from other client sockets.

(4) Common sockets are divided into two main types:

A. Streaming socket: a communication based on TCP protocol, that is, the communication between the two parties to confirm the identity and establish a connection channel, and then transfer data through this channel.

B. Datagram socket: a UDP protocol-based communication, without the need for communication between the two sides to establish a connection, but directly to the message package to the specified destination.

(5) streaming socket programming

The socket class and the ServerSocket class are defined in the java.net package, which are the main tools for implementing streaming socket communication. Creating a Socket object creates a client-to-server connection, and creating a ServerSocket object creates a listening service.

A. Socket class : You can establish a client-server connection by constructing a socket object. The socket class is constructed as follows:

Socket (String host,int Port)

Socket (inetaddress address,int Port)

Socket (inetaddress address,int port,inetaddress localaddr,int localport)

Where host, port, and address represent the hostname, port number, and IP addresses of the connected host, LOCAADDR represents the IP address of the local host, and LocalPort represents the local host port number. For example:

Socket mysocket = new socket ("www.sina.com", +);

Note: Each port number provides a specific service, and only the correct port is given to obtain the appropriate service. The port number for the 0~1023 is reserved for the system, for example, the port number of the HTTP service for the 80,telenet service has a port number of 23,FTP service port number of 21.

After you create a new socket object, you can use its getInputStream () method to obtain a inputstream stream, which can then receive information from a host by InputStream object, using Getoutputstream () You can get a OutputStream object that can be used to send information to a host. For example:

Public class getdaytime{

public static void Main (string[] args) {

try{

Socket socket = new Socket ("stdtime.gov.hk", 13);

BufferedReader br = new BufferedReader (New Inputstrea Mreader (Socket.getinputstream ()));

String daytime = Br.readline ();

System.out.println ("Daytime Received:" +daytime);

Socket.close ();

}catch (IOException e) {

System.out.println ("ERROR:" +e);

}

}

}

B. ServerSocket class

The ServerSocket class represents a server in both sides of the communication that listens to and processes connection requests sent by the client. You can create a ServerSocket object by passing the port number that the server listens on to the ServerSocket constructor. The ServerSocket class is constructed as follows:

serversocket (int port);

ServerSocket (int port,int count);

Where port represents the port number, and count indicates the maximum number of connections that the server can support. For example:

ServerSocket serversocket = new ServerSocket ();

This specifies that the port number that the server listens on is 5000. After you create a ServerSocket object, you can call the Accept () method to accept the request from the client. The format is:

Socket socket = serversocket.accept ();

The Accept () method of the ServerSocket object causes the server-side program to block until a request from the client is captured and an object of the socket class is returned to handle communication with the client.

When you need to end the listener, you can close the ServerSocket object using the following statement:

serversocket.close ();

(6) Data report socket programming

The Datagrampacket and Datagramsocket classes are provided in the java.net package to support non-connected datagram socket communication. The Datagramsocket class is used to establish communication connections between programs that transmit datagrams, and the Datagrampacket class is used to store information such as datagrams.

A. Datagramsocket class : Construction method is as follows:

Datagramsocket ();

Datagramsocket (int port);

Datagramsocket (int port,inetaddress localaddr);

Where port represents the port number; Localaddr represents the local address.

The Datagramsockt class construction method throws a non-runtime exception socketexception, which the program needs to handle.

B. Datagrampacket class:

When writing a client/server program in the form of a datagram, both the client and the server need to establish a Datagramsocket object to receive or send the datagram, while the Datagrampacket object is the carrier of the datagram transmission. The construction method is as follows:

Datagrampacket (byte[] buf,int length);

Datagrampacket (byte[] buf,int length,inetaddress address,int port);

Where the byte array buf the datagram to be sent or received, the length of the datagram, address, and port indicate the destination and host port number of the datagram sent.

Before receiving data on the client or server side, you should create a Datagrampacket object with the first construction method of the Datagrampacket class, and then call the receive () method of the Datagramsocket class to wait for the datagram to arrive. For example:

datagramsocket socket = new Datagramsocket ();

Datagrampacket packet = new Datagrampacket (buf,256);

Socket.receive ();

Before sending the data, you need to create a new Datagrampacket object using the second construction method of the Datagrampacekt class, that is, to indicate the destination address and port number of the datagram being sent. Send datagrams are implemented through the Send () method of the Datagramsocket class. For example:

datagramsocket socket = new Datagramsocket ();

Datagrampacket packet = new Datagrampacket (buf,length,address,port);

Socket.send (packet);

Java Learning Notes-12th chapter Introduction to Java Networking programming

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.