Java Network programming

Source: Internet
Author: User
Tags domain name server ftp access server port fully qualified domain name

  The so-called computer network, is distributed in different geographical areas of computers and specialized external equipment with a communication line interconnection into a large, powerful network system, so that many computers can easily communicate with each other information, share hardware, software, data information and other resources.    Computer network is the combination of modern communication technology and computer technology, computer network can provide the following main functions.    – Resource sharing.    – Information transfer and centralized processing.    – Balanced load and distribution processing. – Integrated information Services.     Network by scale three categories: Local area network (LAN): Refers to a small geographical range of various computer network equipment interconnection of the communication network, can contain one or more subnets, usually confined to thousands of meters in the range.  Metropolitan Area Network (man), which is mainly made up of interconnection between local LANs within the metropolitan area, is seldom brought up to this concept. Wide area network (WAN): is connected by a distant LAN or metropolitan area network, usually in addition to computer equipment, but also involves a number of telecommunications communication methods. The   TCP/IP layered and OSI layered   TCP/IP protocol set    IP address IP addresses are used to identify a communication entity in the network, which can be a host, It can also be a printer, or a port on a router.  Packets that are transmitted over an IP-protocol network must be identified using an IP address. The IP address is a digital type, the IP address is a 32-bit (32bit) integer, but usually to make it easier to remember, it is usually divided into 4 8-bit binary numbers, each 8 bits separated by dots, each 8-bit integer can be converted to a 0~255 decimal integer, So the IP address we see is often the following: 202.9.128.88.      IP and DNS IP address – Each computer connected to the network is unique – 32 digits, four numbers separated by dots – classes including the network ID and host ID – network include classes A, B, C, and D e–0~126  –128~191–192~223–127.0.0.1–192.168.10.179–10.11.0.1 Domain Name System – Maps a specific IP address to a string – mapped by the Domain Name Server system maintenance   Port A port is a 16-bit integer that represents which communication program the data is given to handle. Thus, the port is the interface between the application and the outside world, it is an abstract software structure, including some data structures and I/O (basic input/outputBuffer Different applications handle data on different ports, there cannot be two programs on the same machine using the same port, the port number can range from 0 to 65535, it is usually divided into three categories: – Recognized port (well known Ports): 0 to 1023,    They tightly bind (binding) some services. – Register port (registered Ports): from 1024 to 49151.    They are loosely bound to some services. -Dynamic and/or private ports (and/or private Ports): from 49152 to 65535, these ports are dynamic ports used by applications, which are generally not actively used by applications.   used to implement inter-program communication commonly used ports   inetaddress Java provides the InetAddress class to represent the IP address, inetaddress There are 2 sub-classes: inet4address,  Inet6address, which represent the Internet Protocol version 4 (IPV4) address and the Internet Protocol version 6 (IPV6) address, respectively.    The InetAddress class does not provide a constructor, but instead provides two static methods to get the InetAddress instance:  –getbyname (String host): Gets the corresponding InetAddress object based on the host.  –getbyaddress (byte[] addr): Gets the corresponding InetAddress object based on the original IP address.    InetAddress also provides the following three methods to obtain the IP address and hostname of the inetaddress instance: –string getcanonicalhostname (): Gets the fully qualified domain name for this IP address.    –string gethostaddress (): Returns the IP address string (as a string) corresponding to the InetAddress instance. –string gethostname (): Gets the host name of this IP address.  The   urldecoder and Urlencoder Urldecoder classes contain a decode (string s,string Enc) static method that can turn a special string that looks garbled into a normal string. The Urlencoder class contains a encode (String s,string Enc) static method thatYou can convert a normal string into a application/x-www-form-urlencoded mime string.  urlThe URL (Uniform Resource Locator) object represents the Uniform Resource Locator, which is a pointer to the Internet "resource". A resource can be a simple file or directory, or it can be a reference to a more complex object, such as a query to a database or search engine. Typically, a URL can consist of a protocol name, a host, a port, and a resource. The following format is satisfied:Protocol://host:port/resourcename URLConnectionThe program can send requests to the URL through the URLConnection instance and read the resource referenced by the URL.   Typically creating a connection to a URL and sending a request, reading the resource referenced by this URL requires the following steps: – (1) Create the URLConnection object by calling the URL object OpenConnection () method.    – (2) Set URLConnection parameters and normal request properties.    – (3) If you just send a Get method request, use the Connect method to establish the actual connection between the remote resources, and if you need to send a post-mode request, you need to get the output stream for the URLConnection instance to send the request parameters. – (4) The remote resource becomes available, the program can access the remote resource's header field, or read the remote resource's data through the input stream. The  IP protocol IP protocol is a key protocol used on the Internet, and its full name is the Internet Protocol, the Internet protocol, usually referred to as the IP protocol.  By using the IP protocol, the Internet becomes a network that allows connections between different types of computers and different operating systems. The IP protocol only guarantees that the computer can send and receive packet data. The IP protocol is responsible for transmitting messages from one host to another, and the messages are split into packets during the transfer process.   java TCP/IP protocol support TCP/IP communication protocol is a reliable network protocol, it establishes a socket at both ends of the communication, thus forming a network virtual link between the two ends of the communication. Once a virtual network link is established, the programs on both ends can communicate through the virtual link. Java provides a good encapsulation of TCP protocol-based network traffic, and Java uses the socket object to represent the communication interfaces on both ends and to generate IO streams through the socket for network communication. The   TCP protocol TCP protocol is called an end-to-end protocol.  This is because it plays an important role in connecting two computers: When one computer needs to connect to another remote computer, the TCP protocol lets them establish a connection: the virtual link used to send and receive data. The TCP protocol is responsible for collecting these packets and placing them in the appropriate order, and then restoring them correctly after receiving the received side. The TCP protocol guarantees that the packets are accurate in the transmission.  The TCP protocol uses a resend mechanism: when a communication entity sends a message to another communication entity, it needs to receive another communication entity acknowledgment, and if no acknowledgement is received from another communication entity, the information just sent is re-sent. Through this mechanism, the TCP protocol provides a reliable communication connection to the application, enabling it to automatically adapt to various changes on the web. Even in the event of a temporary Internet blockage,TCP can also guarantee the reliability of communication. The   serversocket ServerSocket object is used to listen for a socket connection from the client and will remain in the waiting state if there is no connection. The ServerSocket contains a method to listen for requests from a client connection: Socket Accept (): If a connection request to a client socket is received,  The method will return a socket corresponding to the client socket (17.4 shows each TCP connection has two sockets), otherwise the method will remain in the waiting state and the thread will be blocked. To create the ServerSocket object, the ServerSocket class provides the following constructors: –serversocket (int port): Creates a serversocket with the port specified.    The port should have a valid port integer value: 0~65535.    –serversocket (int port,int backlog): Adds a parameter backlog to change the length of the connection queue. –serversocket (int port,int backlog,inetaddress localaddr): In the case of multiple IP addresses on the machine, Allows you to specify that the ServerSocket be bound to the specified IP address by localaddr this parameter.    socket clients can typically use the socket's constructor to connect to a specified server, which typically uses the following two constructors: –socket (inetaddress/string remoteaddress    , int port): Creates a socket connected to the specified remote host, remote port, which does not specify a local address, local port, default IP address for the local host, and the system dynamically specifies the IP address by default. –socket (inetaddress/string remoteaddress, int port, inetaddress localaddr, int localport):: Creates a Socket connected to the specified remote host, remote port, and specify a local IP address and a local port number for situations where the local host has multiple IP addresses.    network communication when the client, the server side generated the corresponding socket, at this point to 17.4 of the communication, the program no longer distinguish between the server, the client, but through the respective sockets to communicate, soCket provides the following two ways to get the input and output streams: –inputstream getinputstream (): Returns the input stream corresponding to the socket object, allowing the program to extract data from the socket through the input stream. –outputstream Getoutputstream (): Returns the output stream corresponding to the socket object, allowing the program to flow through this output to the socket for output data. The    client establishes the object through the socket and specifies the service-side host and port to connect to.
Socket s = new socket ("192.168.1.1", 9999), outputstream out = S.getoutputstream (); Out.write ("Hello". GetBytes ()); S.close ();

Service side

Set up a server to listen to a port

ServerSocket ss = new ServerSocket (9999); Socket s = ss.accept (); InputStream in = S.getinputstream (); byte[] buf = new Byte[1024];int num = In.read (BUF); String str = new string (buf,0,num); System.out.println (S.getinetaddress (). toString () + ":" +str); S.close (); Ss.close ();

  

Thinking

  For a Web server, how does the server provide services when there are multiple clients accessing the servers at the same time?     joining multi-threaded support the client in the real-world application may need to maintain long-time communication with the server, that is, the server needs to continuously read the client data and write the data to the client, and the client needs to continuously read the server data and write the data to the server. When the data is read using the traditional BufferedReader ReadLine () method, the thread is blocked before the method returns successfully, and the program cannot continue execution.  For this reason, the server should start a single thread per socket and each thread is responsible for communicating with one client. The thread that the client reads the server data is also blocked, so the system should start a separate thread that is specifically responsible for reading the server data.   nio implementing non-blocking communication   Java NIO provides a few special classes for non-blocking socket communication: –selector: It is a multiplexer for Selectablechannel objects, All channel that wants to communicate in a non-blocking manner should be registered with the Selector object.    You can create a selector instance by calling the static open () method of this class, which uses the system default selector to return the new selector. –selectablechannel: It represents a channel object that can support non-blocking IO operations, which can be registered to selector, which is represented by a Selectionkey instance.    The Selector object provides a select () method that allows the application to monitor multiple IO Channel simultaneously.    –selectionkey: This object represents the registration relationship between Selectablechannel and selector. –serversocketchannel: Supports non-blocking operations, corresponds to the Java.net.ServerSocket class, provides the TCP protocol IO interface, only supports op_accept operations.    The class also provides the accept () method, which is equivalent to the Accept () method provided by ServerSocket. –socketchannel: Supports non-blocking operations, corresponds to the Java.net.Socket class, provides the TCP protocol IO interface, supports Op_connect,op_read and op_write operations. This class also implements the Bytechannel interface, the Scatteringbytechannel interface, and the gatherIngbytechannel interface, so you can read and write Bytebuffer objects directly through the Socketchannel. All channel (including Serversocketchannel and Socketchannel) on the   server needs to be registered with selector, and the selector is responsible for monitoring the IO status of these sockets. When any one or more of the channel has an IO operation available, the selector Select () method returns an integer greater than 0, which indicates how many channel on the selector has an IO operation available. The Selectedkeys () method is provided to return the Selectionkey collection corresponding to these channel. It is through selector that the server side only needs to constantly invoke the Select () method of the selector instance to know whether any current channel has an IO operation that needs to be processed. The function of the proxy server of    Proxy server is to obtain network information by proxy network users. When we use a Web browser to connect directly to other Internet sites for network information, we usually need to send request requests to wait for a response. The proxy server is a server between the browser and the Web server, and with it, the browser does not go directly to the Web server to obtain the Web data, but instead makes a request to the proxy server, the request is sent to the proxy server first. The proxy server retrieves the information needed by the browser and sends it back to the Web browser.     using a proxy proxy is like the next constructor: Proxy (Proxy.type Type, socketaddress sa): Creates a proxy object that represents an agent server.  The SA parameter specifies the address of the proxy server where type is the type of the proxy server, which has the following three types: –proxy.type.direct: Indicates that a direct connection or proxy does not exist.  –proxy.type.http: Represents a proxy for advanced protocols, such as HTTP or FTP.  –proxy.type.socks: Represents the SOCKS (V4 or V5) proxy.  Once the proxy object is created, the program can use URLConnection to open the connection, or to pass in a proxy object when creating the socket connection, as the proxy server used for this connection. Where the URL contains a URLConnection OpenConnection method that uses the specifiedProxy server to open the connection, and the socket provides a socket constructor that uses the specified proxy server to create a socket object that is not connected.     use Proxyselector proxyselector to use a different proxy server depending on the connection. The system default Proxyselector detects various system properties and URL protocols, and then decides how to connect to different hosts.  Of course, the program can also call the SetDefault () static method of the Proxyselector class to set the default proxy server, or you can call the Getdefault () method to get the system's current default proxy server. The system class can be used to set the proxy server properties, and there are three common property names for the proxy server: –http.proxyhost: Sets the proxy server address used by HTTP access.    The prefix for this property name can be changed to HTTPS, FTP, and so on, respectively, to set the proxy server address used for HTTP access, secure HTTP access, and FTP access. –http.proxyport: Sets the proxy server port used by HTTP access.    The prefix for this property name can be changed to HTTPS, FTP, and so on, respectively, to set the proxy server port used for HTTP access, secure HTTP access, and FTP access. –http.nonproxyhosts: Set up a remote host in HTTP access that does not require a proxy server, you can use the * wildcard character, and if there are multiple addresses, multiple addresses are separated by a vertical bar (|).   Custom ProxyselectorThe system provides the default Proxyselector subclass as the proxy selector, the developer can implement their own proxy selectors, the program can inherit the Proxyselector to implement their own proxy selectors. Inheriting proxyselector requires rewriting two methods:–list<proxy> Select (Uri uri): This method enables the proxy selector to use a different proxy server depending on the URI, which is the key to the proxy selector to manage network connections using a proxy server. –connectfailed (Uri Uri, socketaddress sa, IOException IoE): The proxy selector will call this method automatically when the system fails to establish a connection through the default proxy server. You can override this method to process a failure of the Connection Broker server.

Java Network programming

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.