Network Programming 1

Source: Internet
Author: User
Tags file transfer protocol

Network programming
The Java language provides a powerful network programming function, can handle a variety of network resources and network communication, so that users can use fluent and perfect way to achieve network programming, complete a variety of complex network application development. The main work of network programming is to send the information through the planned protocol to assemble the package, at the receiving end in accordance with the agreed protocol to the package to parse, so as to extract the corresponding information, to achieve the purpose of communication. Among them, the most important is the assembly of data packets, packet filtering, packet capture, data packet analysis, of course, finally to do some processing.
Fundamentals of Network programming
Network traffic for Java can use TCP, IP, and UDP protocols. These protocols are briefly described before Java network programming.
What is the TCP protocol
TCP (trasnsmission Conctrol Protocol) is the Transmission Control protocol, which is the network transport layer of protocols, mainly responsible for data grouping and reorganization. The TCP protocol provides a reliable data transfer service, which is connection-oriented, and most network applications use the TCP protocol to implement the transport layer. It is very easy to create a network application using the TCP protocol, which can guarantee the time of data transfer. The order and content are correct. But using TCP requires a lot of network overhead, so if you want to achieve more efficient transmission, TCP is not appropriate. The main features of the services provided by TCP are as follows:
Connection-oriented transport
End-to-end communication
High reliability, ensuring the correctness of transmitted data without loss or confusion
Full Duplex mode transmission
Byte stream, that is, byte sequence is transmitted in bytes
Emergency data transfer function

What is an IP protocol
IP is an abbreviation for Internet Protocol (the protocol of interconnection between networks), which is called "Network Association", which is the protocol designed by the computer network to communicate with each other. In the Internet, it is a set of rules that enable all computer networks connected to the Internet to communicate with each other, providing for the rules that computers should observe when communicating on the Internet. Computer systems produced by any manufacturer can be interconnected with the Internet as long as they comply with the IP protocol.
IP represents the unique identity of each computer in the network and is a lower-level protocol than TCP. IP addresses are unique and can be divided into 5 categories depending on the nature of the user. In addition, IP also has access to protection, intellectual property, pointer registers and other meanings.
An IP address is a 32-bit (IPV4) or 128-bit (IPV6) unsigned number that uses 4 sets of numbers to denote a fixed number, separated by a dot number, such as "172.168.1.52", which represents the unique address number of a computer in the network.

What is TCP/IP
TCP/IP (transmission conctrol potocol, Internet potocol), Transmission Control Protocol/Internet Protocol, is an industry-standard protocol set designed for wide area networks (WANs). It was developed by the research institutions of the Appanet network.
Sometimes we describe TCP/IP as an Internet Protocol set (Internetpotocolsuite), where TCP and IPs are the two protocols. Because TCP and IP are familiar protocols, it is used to replace the entire protocol set with the word TCP/IP or IP/TCP. This is a bit strange, but there is no need to dispute the habit. For example, sometimes we discuss that NFS is based on TCP/IP, although it does not use TCP at all (IP and another interactive protocol UDP instead of TCP)

What is a UDP protocol
UDP (user Datagram Potocol) refers to the Subscriber packet protocol. Like the TCP protocol, it is a protocol on the network transport layer, but it is fundamentally different from TCP. Transmission using UDP protocol is, does not guarantee that the data must be able to reach the destination, and does not guarantee the order of arrival. However, the UDP protocol occupies less resources, so it is generally used in some low reliability requirements of the network applications, such as network video conferencing, online film and chat rooms and other audio, video data transmission.

What is a port
Port can be understood as a window into which the computer communicates with the outside world. A computer on the network can provide multiple services, such as Web services, FTP services, and Telnet services. So, how do you divide these services? Relying solely on an IP address is not possible, because the same computer's IP address is the same. In fact, different services can be distinguished by the "IP address + port number" form. When the information arrives, depending on the port number, you can know which service should be provided.
Common port services:
Http:80
Ftp:21
Telnet:23
Smtp:25

What is a socket
Socket (socket) is a basic operating unit that supports TCP/IP network communication, it can be regarded as the cross-sectional point of process bidirectional communication between different hosts, and simply means a contract between two sides of the communication, using the correlation function in socket to complete the communication process. A program writes a piece of information to the socket, which sends the message to the other socket, just like the ends of the phone line, so that another section of the program receives the message through a socket on the other end. Therefore, using socket programming is sometimes referred to as socket programming.

java.net Bag
In the Java API, the java.net package is used to provide network services. The java.net package contains a variety of classes specifically designed to develop network applications, and program developers use the classes in the package to easily establish network programs based on TCP reliable connections, as well as network programs based on UDP unreliable connections. The java.net package is broadly divided into the following two parts.
Low-level API: Used to process network addresses (that is, network identifiers, such as IP addresses), sockets (that is, the basic data bidirectional communication mechanism) and interfaces (for describing network interfaces).
Advanced API: For handling URIs (representing Uniform resource identifiers), URLs (representing Uniform Resource Locators), URLConnection connections (representing connections to resources that the URL points to), and so on.

InetAddress class
Any host running on the Internet has an IP address and a domain name that the local DNS can resolve. The wrapper class inetaddress for the IP address is provided in the java.net package.
The InetAddress class is used to describe and package a Interneti address, and provides relevant common methods, such as parsing the host name of the I-chip address, getting the local IP address closed, testing whether the specified IP address can be reached, and so on. InetAddress implements the Java.io.Serializable interface and does not allow inheritance. It returns the InetAddress instance using the following 3 methods.
Getlocalhost (): Returns an instance of the encapsulated local address
Getallbyname (String host) returns an array of inetaddress instances that encapsulate the host address.
Getbyname (String Host): Returns an instance that encapsulates the host address. Where host can be a domain name or a legitimate IP address

Common methods of InetAddress class
Method Name Method Description return type
Getlocalhost () returns the InetAddress object of the local host InetAddress
Getbyname (String Host) returns the IP address of the specified host name inetaddress
Getallbyname (String host) returns an array inetaddress array of specified host names
GetHostName () Gets the local host name String
Gethostaddress () Gets the local host address String
isreachable (int timeout) in the specified time (milliseconds), test whether the IP address can reach Boolean

In these static methods, the most common should be the Getbyname (String host) method, only need to pass in the name of the destination host, InetAddress will try the level two DNS server, and obtain the operation of the IP address. The code snippet is as follows: Assuming that the following code is the default import java.net package, add import java.net.* at the beginning of the program, otherwise you need to specify the full name of the class java.net.InetAddress.
InetAddress address=inetaddress.getbyname ("www.baidu.com");
Note These methods may throw exceptions. If the security management area does not allow access to the DNS server or prohibits network connections, SecurityException throws, or throws Unknowhostexception, if the corresponding host's IP address is not found or other network I/O errors occur. So you need to write the following code:

Try {inetaddress address=inetaddress.getbyname ("www.baidu.com"); SYSTEM.OUT.PRINTLN (address);} Catch (unknowhostexception e) {e.printstacktrace ();}}


The following example uses the InetAddress class to obtain the relevant network information, with the following code:

Importjava.net.*; Public classtest1{ Public Static voidMain (String []args)throwsexception{inetaddress ia=NULL;//defining the variable iaTry{ia=inetaddress.getlocalhost ();}Catch(unknowhostexception e) {e.printstacktrace ();}//get the InetAddress object for this machineSYSTEM.OUT.PRINTLN ("Host name for this machine:" +ia.gethostname ()); System.out.println ("The IP of this machine is:" +ia.gethostaddress ());}}

URL Network programming
Many high-level network classes are available in the Java class Library. Where the URL (Uniform Resource Locator) class is such a network class.
Url
A URL is a uniform Resource locator that represents the address of a resource on the Internet, also known as a Web page address. URLs allow developers to access various resources on the Internet, such as Common WWW services or FTP services. By parsing the URL, the browser can find resources like the corresponding. For example, here is Google's address:
http://www.google.com
This URL consists of two parts: the protocol identifier and the resource name. Where "http" is the usage protocol, it refers to Hypertext Transfer Protocol (HTTP). Other commonly used protocols include File Transfer Protocol (FTP), Gopher, files, and news.
The URL also provides several methods for obtaining the URL's object protocol, host name, port number, path, query string, file name, and resource reference. The common methods for URLs are as follows:
Method Name Method Description
Getpotocol () Get the protocol name of the URL
Getauthority () get the host name and port number of the URL
GetFile () Gets the file name of the URL
GetHost () Gets the hostname of the URL
GetPath () Get the path to the URL
Getport () Gets the port number of the URL
Getquery () Gets the query string for the URL
GetRef () obtains the URL's reference anchor named

Character syntax
The authorization section is typically the name or IP address of the server, sometimes followed by a colon and a port number. It can also contain user names and passwords that must be exposed to the server. The path section contains the path definition for the hierarchy, in general, separated by/(slash) between the different parts. The query section is typically used to transfer parameters that are required to dynamically query the database on the server. Complete, the common Uniform Resource Identifier syntax with the authorization section is as follows:
Protocol://username @ Password: subdomain. Domain name. Top-level domain: Port number/directory/file name. filename suffix? parameter = value # flag
The Uniform Resource Identifier reference refers to a single, uniform resource identifier, such as in a Hypertext Transfer protocol file. Uniform Resource Identifiers Reference Absolute Reference and relative reference. All of the above are absolute Uniform Resource Identifier references, the relative reference contains only the special parts of the system, and its reference object is located in a relative position containing the reference file. The Uniform Resource Identifier reference can also be represented by a Uniform Resource identifier plus a # character plus a flag point within the Uniform Resource identifier above. This flag point is not part of the uniform identifier, but rather allows the user's browser to navigate after obtaining the file, so it is not actually transmitted to the server. Here are the various ways to use URLs through an instance, with the following code:

Importjava.net.*;ImportJava.io.*; Public classtest2{ Public Static voidMain (String []args)throwsException{url Aurl=NULL;Try{Aurl=NewURL ("http://www.google.com:80");}Catch(malformesurlexception e) {e.printstacktrace ();//output URL Object protocolSystem.out.println ("protocol=" +Aurl.getprotocol ());//the host name and port name of the object that outputs the URLSystem.out.println ("authority=" +aurl.getauthority ());//host name of the output URLSystem.out.println ("host=" +aurl.gethost ());//get the port for the URLSYSTEM.OUT.PRINTLN ("Port" +Aurl.getport ());}}



The results of the operation are as follows:

protocol=httpauthority=www.google.com:80Host=www.google.comport=80

It is important to note that the main () method declaration in the Parseurldemo class throws an exception that is handled by the system, so the exception is not handled in the code using the Try/catch statement.

URLConnection class
The URLConnection class is used to represent a communication connection established with a URL. In the java.net package, call the OpenConnection () method of the URL class to get the URLConnection object. Once the object is obtained, the developer can invoke the Connect () method of the object to connect to the remote resource, with the following code:

Try {URL Wy=new URL ("http://www.163.com/"); URLConnection wyconnection=wy.openconnection (); // get URLConnection Object wyconnection.connect (); // Connecting remote Resources }catch(Malformedurlexceeption e) {// Create URL fails when this exception is generated }  This exception occurs when the catch (IOException e) {///OpenConnection () method fails }

After the

is connected to a remote resource, you can perform related actions, including querying HTTP request header information, accessing resource data, and writing related content. Throws an exception in the main () method declaration, which is handled by the system, so the code uses the Try/catch statement to handle the exception.
While reading the content is the same as the OpenStream () method of the URL, but using the Getoutputstream () method of the URLConnection class to get the output stream can also write data like the output stream, at the URL Another single server program can accept the input data.

TCP Network Programming
TCP (Transmission Control Protocol) is a connection-based protocol that provides reliable data transfer between computers. The two ends of the connection channel are often referred to as sockets (sockets), which is also true for TCP-based network traffic, where connections are established and data is sent and received via sockets. The two sides of a
Socket
communicating over TCP are commonly referred to as the server side and the client. The server side and the client can be two different computers or the same computer. Server-side running is a server-side program, and running the Hey client program is different.
Depending on how the connection is started and the destination to which the local socket is connected, the connection between sockets can be divided into 3 steps: Server listening, service-side request, connection acknowledgement.
Server listening: refers to server-side sockets, not locating specific client sockets, but in a state of waiting for the connection, real-time monitoring network status.
Client request: Refers to a connection request made by the client's socket, and the target to connect to is the server-side socket. To do this, the client's socket must first describe the socket of the server it is connecting to, indicate the address and port number of the server-side socket, and then make a connection request to the server-side socket.
Connection acknowledgement: Refers to the server socket that listens for incoming connection requests to a client socket, it responds to a client socket request, establishes a new thread, and sends a description of the server-side socket to the client. Once the client confirms this description, the connection is established, and the server-side socket continues to be listening, continuing to receive socket connection requests from other clients.
in the java.net package, there is a socket class that is used to establish the socket. The java.net package also has a ServerSocket class, which is used on the server side, which has an accept method that listens to and receives client connection requests. The Java.net.Socket class is a socket class that is used by both the server side of the development Network application and the client program. It provides a number of ways to get relevant information.
Common methods for the socket class
Method name method Description
getInputStream () get input stream from Socket
Getinetaddress () Get network address from Socket
Getlocaladdress () Get the local network address
Getport () get the port in the socket
Getlocalport () Get the native port
Getoutputstream () get the output stream from the socket
Close () Close socket

The

Important socket API
Java.net.Socket inherits from Java.long.Object, with 8 constructors, not many methods. The 3 most frequently used methods are described below: the
Accept () method: Used to generate "blocking" until a connection is accepted and a client's socket object instance is returned. "Blocking" is a term that causes a program to run temporarily "stuck" in this place until a session is generated, and then the program continues; usually "blocking" is generated by loops.
getInputStream () method: Gets the network connection input and returns an InputStream object instance.
Getoutputstream () method: The other end of the connection will get input and return a OutputStream object instance, note that Both the getInputStream and Getoutputstream methods may produce a ioexception, which must be captured because the stream object they return is typically used by another stream object.

Server-side programming
Server-side programs need to use the Java.net.Socket class and the Java.nt.ServerSocket class. The establishment of a server-side program typically requires the following 5 steps:
1: In a server-side program, you first create an instance object of Class Java.net.ServerSocket, register the port number to connect on the server side, and the maximum number of users allowed to connect.
2: Call the Member method of ServerSocket accept (), wait and listen for connections from the client. When a client establishes a connection to the server side, the Accept () method returns the socket on the server side of the socket Connection channel. The socket enables data communication with the client.
3: Call the server-side socket socket Method getInputStream () and Getoutputstream () to obtain the corresponding input stream (InputStream) and output stream (Ouputstream) for the socket.
4: Data communication with the client's memory by obtaining the input stream and output stream, and processing data obtained from the client and to be sent as the client.
5: After the data transfer is complete, turn off the input stream, output stream, and socket.
After the server-side creates an instance object of ServerSocket and calls its accept () method, the service side begins to wait for the client to connect to it. The common methods of the ServerSocket class are as follows:
Method Name Method Description
The Accept () blocker waits for a client connection request. Once a connection request is received, a socket object indicating that the connection has been established is returned.
Close () closes the current socket
Getinetaddress () Get the network address of this machine
Getlocalport () Get the listening port


The following is an example of a service-side program for a simple Web application. The function of the program is to read the connection request of the listening client and send the greeting message to the client, and when the customer sends over "end", the connection ends. The code is as follows:

ImportJava.io.*;Importjava.net.*; Public classtest300 { Public Static voidMain (String []args)throwsioexception{Importjava.net.*; Public classtest300 { Public Static voidMain (String []args)throwsIoexception{serversocket Server=NULL;Try{Server=NewServerSocket (5678);}Catch(IOException e) {e.printstacktrace ();}//Create a ServerSocket instance with the port number of the listenerSYSTEM.OUT.PRINTLN ("The server is starting properly, waiting for a connection ....") "); Socket Client=NULL;Try{Client=server.accept ();}Catch(IOException e) {e.printstacktrace ();}//blocking, waiting for client connectionsSYSTEM.OUT.PRINTLN ("Client is establishing a connection");//get the byte input stream of the socket connection and convert it to a buffered character streamBufferedReader in=NewBufferedReader (NewInputStreamReader (Client.getinputstream ()));//Job socket connection print output streamPrintWriter out=NULL;Try{ out=NewPrintWriter (Client.getoutputstream ());}Catch(IOException e) {e.printstacktrace ();} while(true) {String str=In.readline (); System.out.println (str); OUT.PRINTLN ("Accepted ... "); Out.flush ();if(Str.equals ("End"))//if the client sends over end, the connection is closed.  Break;} In.close (); Out.close (); Client.close (); Server.close ();}}

The results of the operation are as follows:
Server is started, waiting for connection ...
As shown in the preceding code, first use the serversocket (int port) constructor on the server side to construct a ServerSocket server-side socket instance. Where the parameter port is the ServerSocket class to listen on. There are 4 constructors that can be used to create serversocket. As shown below:

ServerSocket server1=New  serversocket (); ServerSocket server2=new serversocket (5678); ServerSocket Server3=new serversocket (5678,100); ServerSocket server4=new serversocket (int port,int backlog,inetaddressbindaddr);

The constructor with no parameters is the default construction method, and can be commonly used as a server socket for binding port numbers. A constructor with one parameter will create a server socket object that is Baoding to the specified port, and the default maximum understanding queue Length is 50. If there are more than 50 connections, there will be no more new connection requests. A constructor with two parameters creates a server socket object with the port number specified by the parameter and the maximum connection queue length. And the last construction method, when the server has multiple IP addresses, use the BINDADDR parameter to know the IP address that created the server socket.

Network Programming 1

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.