Fundamentals of Java Network programming

Source: Internet
Author: User
Tags get ip domain name server

Network Transport Protocol

InetAddress class

The Socket class understands:

Socket common methods

TCP-based socket programming

UDP-based socket programming

URL programming

Summarize

Java Network programming

Java is inherently a language that supports the Web. Java provides a network class library, can easily achieve network connectivity, and the underlying details of the internet is hidden in the Java local installation system, controlled by the JVM, Java implemented a cross-platform network library, so programmers face a unified network programming environment.

Two problems with network programming:

1 How to accurately locate one or more hosts on the network

2 How to reliably and efficiently transfer data.

IP address and port number

IP Address: Uniquely identifies a computer on the Internet

Two representations of IP: Hostaddress host address (commonly known as IP)

HostName hostname (commonly known as domain name) domain name requires DNS domain name server to resolve to the IP address, scope.

Note Local loopback address: 127.0.0.1 Local host name: localhost

"Understand" when the browser issued a domain name request, first find the local hosts, directories as follows C:\Windows\System32\drivers\etc\hosts, to see if there is an input domain name address, no, then through the DNS server, resolve the domain name, access to the host.

Port number: Identifies the program that is running on the computer.

1, different programs have different port numbers;

2, the port number is specified as a 16-bit integer, 0~65535. where 0~1023 "Well-known-ports" is used by pre-defined service communications (Mysql occupies 80, etc.) unless we need to access these specific services, we should use 1024~65535 "Dynamic Ports "One of these ports communicates to avoid port collisions.

A network socket is derived from the combination of the port number and IP address.

mysql:3306 tomcat:8080; Ftp:21

HTTP:80 oral:1521; Telnet:23 ssh:22

The InetAddress class in Java

    • InetAddress: Located under the java.net package

      • The 1.InetAddress class is used to represent an IP address. A Inetadress object represents a specific IP address.

      • 2. How to create a InetAddress object: A static method of the InetAddress class,

Getbyname (String host)

    • 3.getHostName (): Gets the domain name corresponding to the IP address

Gethostaddress (): Get IP Address

The InetAddress class does not provide a constructor for the external, usually with the following two methods to obtain an instance of the InetAddress class.

Getbyname (String host) determines the IP address given the host name and returns an instance of the InetAddress class. The parameter can be a string form of a domain name or IP.

Getbyaddress (byte[] address) Returns an instance of the InetAddress class in the case of a given IP address.

Getlocalhost () Returns an instance of the local host's InetAddress class.

Gethostaddress () returns the string form of the host IP address.

GetHostName () returns the string form of the host domain name

isreachable (int timeout) can be accessed by the host in a timeout (milliseconds) period.

Getcanonicalhostname () returns the fully qualified name string form of the host.

Data Transfer Encapsulation Model:

Network Transport Communication Protocol

Network communication protocol is a standard to regulate the transmission rate, transmission code, code structure, Transmission control steps, error control and so on.

Layered thinking of communication protocols:

The links between the nodes are complex, and when the protocol is developed, the complex components are decomposed into several simple components, which are then combined together. And the most common way of compounding is

Hierarchical mode, that is, the same layer can communicate, the previous layer can call the next layer, and the next layer does not have a relationship between the layers of each other, conducive to the development and expansion of the system.

Based on the understanding of the above communication protocols, the two most common protocols in the Transport Layer protocol are:

1 Transmission Control Protocol TCP (transmission-Protocol)

2 Subscriber Packet Protocol UDP (user Datagram Protocol)

TCP protocol:

Before using the TCP protocol, you must first establish a TCP connection to form a transport data channel

High reliability thanks to the "three-time handshake" method prior to transmission

Two application processes for communication with the TCP protocol client & server side

Large amount of data can be transferred in the connection

Transfer completed, need to release the established link, inefficient

UDP protocol:

Encapsulates data, sources, and purposes into packets without the need to establish a connection

Limit the size of each packet within 64k

Because there is no need to connect, it is unreliable

At the end of the sending packet, there is no need to free up resources, fast.

Socket Understanding:

A socket is a combination of a set of port numbers and IP addresses.

Using sockets to develop Web applications has been widely adopted and has become a standard.

A socket is needed on both ends of the communication.

Network communication is actually the communication between sockets.

The socket allows the program to treat the network connection as a stream, and the data is transmitted via IO between two sockets.

An application that typically initiates communication is a client-side server that waits for one end of a communication request.

Socket-based TCP programming process:

Common methods for socket classes

InetAddress getLocalAddress() 返回本地Socket中的InetAddress 对象。InetAddress getInetAddress()  返回对方Socket 中的InetAddress 对象。int getLocalPort() 返回本地Socket 中的端口int getPort() 返回对方Socket 中的端口void close() throws IOException 关闭Socket,不可在以后的网络链接中使用,除非创建新的SocketInputStream getInputStream() throws IOException 获取与Socket相关联的字节输入流,用于从Socket中读数据。OutputStream getOutputStream() throws IOException 获取与Socket相关的字节输出流,用于从Socket中写入数据。

Socket-based TCP programming

1 Create socket: Constructs the socket class object based on the IP and port of the specified server. If the server-side response, establish a client-to-server communication line, if the connection fails, an exception occurs.

2 Open the input/output stream connected to the socket: using the Socket object's

The getInputStream () method obtains the input stream and uses the Getoutputstream () method to obtain the output stream.

3, read and write the socket according to a certain protocol: the input stream reads the information from the server into the line (but cannot read the information it puts into the line), and writes the information to the line through the output stream.

4. Close the socket, disconnect the client from the server, and release the line.

Part of the code that is implemented specifically:

The client program can use the socket class to create an object, and it will automatically initiate a connection to the server side.
The socket is constructed by: socket (String host,int port) throws Unknownhostexception,ioexception
To the server (the domain name is host.) Port number Port) initiates a TCP connection and, if successful, creates a socket object, or throws an exception.
Socket (inetaddress address,int Port) throws IOException: Initiates a connection based on the IP address and port number represented by the InetAddress object. The procedure for a client to establish a socket object is to make a socket connection request to the server
Socket s = new socket ("192.168.40.165", 9999);
OutputStream out = S.getoutputstream (); Out.write ("Hello". GetBytes ());

S.close ();

Server-side four basic steps:

1, Call ServerSocket (intPort): Creates a server-side socket and binds to the specified port. A request to listen for a client. The following code may have a IOException exception in this case. ServerSocket SS =NewServerSocket (9999);2, call Accept (): Listens for connection requests and, if the client requests a connection, accepts the connection and returns the communication socket object. Accepting a client's socket is also prone to ioexception exceptions. Note that the Accept () method returns a socket object, but this method does not return immediately, which blocks the execution of the current thread on the server side until the client requests a socket connection. Socket s = ss.accept (); Note: The ServerSocket object can call Setsotimeout (intTimeout) method to set the time-out value (in milliseconds) when the ServerSocket object calls the Accept () method to block when the timeout is exceeded sockettimeoutexception3, the Getoutputstream () and getInputStream () of the socket class object are called to get the output stream and the input stream to begin sending and receiving network data. InputStreaminch= S.getinputstream (); byte[] buf =Newbyte[1024x768];int Len; while((Len=inch. Read (BUF))! =-1){Stringstr =New String(BUF,0,Len); System.out.print (str)}4, close the ServerSocket and socket objects: End of client access, close the communication socket.inch. Close (); S.close (); Ss.close ();

Note:

The ServerSocket object is responsible for waiting for the client to request a socket connection, which means that the server must establish a ServerSocket object that waits for a customer request before establishing a socket connection. The so-called "receive" client's socket request is that the accept () method returns a Socket object Note:

It is important to note that reading data from a socket connection is very different from reading data from a file, although both are input streams, all data is already present in the file when the data is read from the file, and when a socket connection is used, it is possible that the data at the other end is being read before it is sent. This will block this thread until the Read method has successfully read the message, and the line friend continues with the subsequent operation.

After the connection is established, the server-side socket object can call the Getinetaddress () method to get a InetAddress object that contains the client IP. The same client can also call the Getinetaddress () method to return a InetAddress object that contains the server-side IP.

The socket object calls the close () method to close both sides of the socket connection object, which causes the IOException exception to occur whenever a party closes the connection.

UDP network communication

Class Datagramsocket and Datagrampacket implement a network program based on UDP protocol. The UDP datagram sends and receives through the datagram socket datagramsocket, the system does not guarantee that the UDP datagram can be sent to the destination safely, nor is it certain when it can arrive. The Datagrampacket object encapsulates a UDP datagram that contains the IP address and port number of the sending side and the IP address and port number of the receiving end. Each datagram in the UDP protocol gives the full address information, so there is no need to establish a connection between the sender and the receiver

UDP Transmission Flow: 1, create Datagrampacket object, Datagrampacket class to package data, create Datagrampacket object called datagram, its constructor is as follows:

Datagrampacket (byte[] data,int len,inetaddress Add, int port)

Datagrampacket (byte[],int offset,int length,inetaddress add,int Port)

The packet object contains the following characteristics: 1, which contains data 2 specified by the data array, the packet will be sent to the destination address is add, the destination port number is the port of the host, where the second constructor creates a packet object containing data from offset starting at the specified length of data.

Note: Datagrampacket object calls

The public int Getport () method gets the target port number of the datagram,

Public inetaddress Getaddres () method gets the destination address

Public byte[] GetData () method gets the data in the datagram.

2 creates a Datagramsocket object that is responsible for sending datagrams.

Call the parameterless constructor of the Datagramsocket class, as follows

Datagramsocket mailout = new Datagramsocket ();

Mailout.send (package); 3 Create the Datagramsocket object, responsible for receiving the datagram datagramsocket Mailin = new Datagramsocket (int port);

The parameter must be the same as the port number of the datagram to be received.

4 Create a datagram Datagrampacket object to receive,

Call its constructor to build the packet: Datagrampacket (byte[] data,int length); The datagram will accept data of length in byte array.

byte[] data = new data[1024];

int length = 90;

Datagrampacket inpacket = new Datagrampacket (data,length);

5, call the receive (Datagrampacket Inpacket) method of the Datagramsocket object.

Mailin.receive (Inpacket); Note: The Receive () method may block threads until a datagram Datagrampacket is received. The datagram object can call the Getport () method to get the port from which the received datagram originated from the remote host, that is, the originating port number of the packet, and, similarly, to call the Getinetaddress () method to get the originating address of the packet. The packet length should not exceed 8192KB.

Processing the received data:

String str = new String (Inpacket.getdata (), 0,inpacket.getlength ());

System.out.println (str);

6 Closing the Socket object

Note: The sending side and the receiving end are two separate running programs, thread Independent.

URL programming

The basic composition of the URL:

<传输协议>://<主机名>:<端口号>/<文件名>例如: http://192.168.1.100:8080/helloworld/index.jsp

In order to indicate that the class URL is implemented in Url,java.net. We can initialize a URL object by using the following constructor: public URL (string spec): A URL object can be constructed from a string that represents a URL address.

For example: URL URL= NewURL ("http://www. atguigu.com/"); PublicURL (url context,StringSPEC): Constructs a URL object from a base URL and a relative URL. For example: URL downloadurl= NewURL (url, "download.Html") public URL (string protocol, string host, string file); For example: New URL ("http", "Www.Atguigu.Com"," download. HTML "); PublicURL (StringProtocolStringHost, int port,Stringfile); For example: URL Gamelan= NewURL ("http","Www.atguigu.com", the, "Download.Html");

The constructor of a class URL declares that a non-runtime exception is thrown, and this exception must be handled, usually with a try-catch statement. After a URL object is generated, its properties cannot be changed, but the properties can be obtained by the method it is given:

public string  Getprotocol () Gets the protocol name of the url  public string  gethost            () gets the host name of the url  public string  getport () Gets the port number of the url  public string  GetPath () gets the 
    
     url  public 
     string  getFile () gets the 
     url  public 
     string  getquery () gets the 
     url  
     inputstream  openstream (): ① opens a connection to this URL, returning the 
     inputstream . URLConnection openconnection (): Returns the Connection object with 
     url  
     

If you want to output data, such as to the server-side CGI (the Public Gateway Interface Common Gateway Interface, the user browser and the server-side application to connect the interface) program to send some data, you must first establish a connection with the URL, and then read it, You need to use URLConnection at this time.
URLConnection: Represents the connection to the remote object referenced by the URL.

When you establish a connection to a URL, you first generate the corresponding URLConnection object on a URL object by means of the method OpenConnection ().
If the connection process fails, a ioexception is generated
URL netchinaren = new URL ("http://www.atguigu.com/index.shtml"); Urlconnectonn con = netchinaren.openconnection ();
The input and output streams obtained through the URLConnection object can interact with existing CGI programs.

public  Object getcontent  () throws  ioexception Public  int  getcontentlength  () public  String getcontenttype  ()  Public  long  getdate  () public  long  getlastmodified  () public  inputstream getinputstream  () Span class= "Hljs-keyword" >throws  ioexceptionpublic  outputsteram getoutputstream  () throws  ioexception  

Summarize

Computers located on the network have unique IP addresses so that different hosts can differentiate from each other. Client-server is one of the most common network application models.
A server is a hardware or software that provides a specific service to its clients. A client is a user application that accesses a service provided by a server.
A port number is a place of access to a service that distinguishes multiple services on the same physical computer.
Sockets are used to connect the client and server, and each communication session between the client and the server uses a different socket.
The TCP protocol is used to implement a connection-oriented session. The network-related features in Java are defined in the java.net package.
Java uses the InetAddress object to represent an IP address with two fields: Host name (String) and IP address (int).
The class Socket and ServerSocket implement a client-server program based on the TCP protocol.
The socket is a connection between the client and the server, and the details of the connection creation are hidden. This connection provides a secure data transmission channel, because the TCP protocol can solve the data in the transmission process of loss, corruption, duplication, chaos, and network congestion, it guarantees the reliable transmission of data.
Class URLs and URLConnection provide the most advanced network applications. URLs of network resources have the same location to represent various network resources on the Internet. The URL object allows you to create a connection between the current application and the network resource represented by the URL, so that the current program can read the network resource data or send its own data to the network.

Fundamentals of Java Network 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.