1. What is the TCP/IP protocol?
2. What are the two transmission protocols of TCP/IP? What are their respective characteristics?
3. What is a URL?
4. What is the relationship between URL and IP address?
5. What is socket )?
6. What is the relationship between socket and TCP/IP?
7. What is the relationship between URL and socket?
8.1 basic concepts of network programming, TCP/IP Protocol Introduction
8.1.1 basic network knowledge
Network programming aims to communicate directly or indirectly with other computers through network protocols. There are two main problems in network programming: How to accurately locate one or more hosts on the network, and how to transmit data reliably and efficiently after finding the hosts. In TCP/IP, the IP layer is mainly responsible for locating network hosts and routing data transmission. The IP address can uniquely identify a host on the Internet. The TCP layer provides a reliable or unreliable data transmission mechanism for applications, which is the main object of network programming. Generally, you do not need to care about how the IP layer processes data.
Currently, the popular network programming model is the Client/Server (C/S) structure. That is, one Party serves as the server to wait for the customer to make a request and respond. The customer applies to the server when the service is required. The server is always running as a daemon and listens to the network port. Once a customer requests the server, a service process is started to respond to the customer. At the same time, the server continues to listen to the Service port, this allows later customers to get services in a timely manner.
8.1.3 two types of transmission protocols: TCP and UDP
Although the TCP/IP protocol name only has the TCP protocol name, both TCP and UDP protocols exist in the TCP/IP transport layer.
TCP is short for tranfer control protocol. It is a connection-oriented protocol that ensures reliable transmission. It is transmitted over TCP to obtain a sequential error-free data stream. The sender and receiver must establish a connection between two pairs of sockets to facilitate communication based on the TCP protocol. When a socket (usually a server socket) is waiting to establish a connection, another socket can require a connection. Once the two sockets are connected, they can perform bidirectional data transmission, and both parties can send or receive data.
UDP is short for user datasync protocol. It is a connectionless protocol. Each datagram is an independent information, including the complete source address or destination address, it is transmitted to the destination in any possible path on the network. Therefore, the correctness of the arrival time, arrival time, and content cannot be guaranteed.
The following is a simple comparison of the two Protocols:
When UDP is used, the complete address information is provided in each datagram, so there is no need to establish a connection between the sender and the receiver. For TCP, because it is a connection-oriented protocol, a connection must be established before data transmission between sockets. Therefore, a connection is added in TCP.
When using UDP to transmit data, there is a size limit. Each transmitted datagram must be within 64 KB. TCP does not have such restrictions. Once the connection is established, the sockets of both parties can transmit a large amount of data in a unified format. UDP is an unreliable protocol. The data packets sent by the sender do not necessarily arrive at the receiver in the same order. TCP is a reliable protocol that ensures that the receiver fully and correctly obtains all data sent by the sender.
In short, TCP has a strong vitality in network communication. For example, remote connection (Telnet) and file transmission (FTP) both require indefinite data to be reliably transmitted. In contrast, UDP is easy to operate and requires less monitoring. Therefore, it is usually used for client/server applications in distributed systems with high LAN reliability.
Readers may ask, since there is a TCP protocol that ensures reliable transmission, why do we need a non-reliable UDP protocol? There are two main reasons. First, reliable transmission requires a price. The test of the correctness of data content will inevitably take up the processing time and bandwidth of the computer. Therefore, TCP transmission is not as efficient as UDP. Second, in many applications, strict transmission reliability is not required. For example, video conferencing systems do not require absolute correctness of audio and video data, as long as consistency is ensured, in this case, it is more reasonable to use UDP.
8.2 URL-based high-level Java Network Programming
8.2.1 consistent Resource Locator URL
A URL (Uniform Resource Locator) is the abbreviation of a consistent Resource Locator. It represents the address of a resource on the Internet. Through URLs, we can access various network resources on the Internet, such as the most common WWW and FTP sites. By parsing a given URL, the browser can find the corresponding file or other resources on the network.
8.2.2 URL Composition
Protocol: // resourcename
The protocol name (Protocol) indicates the transport protocol used to obtain resources, such as HTTP, FTP, Gopher, and file. The Resource Name (resourcename) should be the complete address of the resource, including a reference in the Host Name, port number, file name, or file. For example:
Http://www.sun.com/protocol name: // host name
Http://home.netscape.com/home/welcome.html protocol name: // machine name + file name
Http://www.gamelan.com: 80/Gamelan/network.html # bottom protocol name: // machine name + port number + file name + internal reference.
8.2.3 create a URL
To represent the URL, java.net implements the class URL. We can use the following constructor to initialize a URL object:
(1) Public URL (string spec );
A URL object can be constructed using a string that represents the URL address.
URL urlbase = new URL ("http: // www. 263.net /")
(2) Public URL (URL context, string spec );
Construct a URL object using the base URL and relative URL.
URL net263 = new URL ("http://www.263.net /");
URL index263 = new URL (net263, "index.html ")
(3) Public URL (string protocol, string host, string file );
New URL ("HTTP", "www.gamelan.com", "/pages/gamelan.net. html ");
(4) Public URL (string protocol, string host, int port, string file );
URL Gamelan = new URL ("HTTP", "www.gamelan.com", 80, "pages/gamelan.network.html ");
Note: The constructor of the class URL declares that the non-runtime exception (malformedurlexception) is discarded. Therefore, when generating a URL object, we must process this exception, it is usually captured using a try-catch statement. The format is as follows:
Try {
URL myurl = new URL (...)
} Catch (malformedurlexception e ){
... }
8.2.4 parse a URL
After a URL object is generated, its attributes cannot be changed, but we can obtain these attributes through the method provided by the URL class:
Public String getprotocol () gets the protocol name of the URL.
Public String gethost () to obtain the Host Name of the URL.
Public int getport () gets the port number of the URL. If no port is set,-1 is returned.
Public String GetFile () gets the name of the URL file.
Public String getref () gets the relative position of the URL in the file.
Public String getquery () gets the query information of this URL.
Public String getpath () gets the URL path
Public String getauthority () to obtain the URL permission information
Public String getuserinfo () get user information
Public String getref () Get the URL's anchor
8.2.5 read WWW Network Resources from URLs
After we get a URL object, we can use it to read the specified WWW resource. In this case, we will use the URL method openstream (), which is defined:
Inputstream openstream ();
Method opensteam () establishes a connection with the specified URL and returns the inputstream class object to read data from this connection.
Public class urlreader {
Public static void main (string [] ARGs) throws exception {
// Declare to throw all exceptions
URL tirc = new URL ("http://www.tirc1.cs.tsinghua.edu.cn /");
// Construct a URL object
Bufferedreader in = new bufferedreader (New inputstreamreader (tirc. openstream ()));
// Use openstream to get an input stream and construct a bufferedreader object.
String inputline;
While (inputline = in. Readline ())! = NULL)
// Read data continuously from the input stream until it is read.
System. Out. println (inputline); // print the read data to the screen.
In. Close (); // close the input stream
}
}
8.2.6 connect to www through urlconnetction
Through the URL method openstream (), we can only read data from the network. If we want to output data at the same time, such as sending some data to the CGI program on the server, we must first establish a connection with the URL before we can read and write it, then we need to use the urlconnection class. CGI is short for the Common Gateway Interface. It is an interface connecting your browser and server applications. For CGI program design, see related books.
The urlconnection class is also defined in the java.net package, which indicates the communication connection between the Java program and the URL on the network. When establishing a connection with a URL, you must first generate the corresponding urlconnection object on a URL object through openconnection. For example, the following program section first generates an object pointing to the address http://edu.chinaren.com/index.shtml. then, open a connection on the URL object with openconnection () and return a urlconnection object. If the connection fails, ioexception is generated.
Try {
URL netchinaren = new URL ("http://edu.chinaren.com/index.shtml ");
Urlconnectonn Tc = netchinaren. openconnection ();
} Catch (malformedurlexception e) {// An error occurred while creating the URL () object.
...
} Catch (ioexception e) {// openconnection () failed
...
}
Urlconnection provides many methods to set or obtain connection parameters. getinputstream () and getourputstream () are most commonly used in programming. They are defined:
Inputsteram getinputsteram ();
Outputsteram getoutputstream ();
Through the returned input/output stream, we can communicate with remote objects. See the following example:
URL url = new URL ("http://www.javasoft.com/cgi-bin/backwards ");
// Create a URL object
Urlconnectin con = URL. openconnection ();
// Obtain the urlconnection object from the URL object
Datainputstream Dis = new datainputstream (con. getinputsteam ());
// Obtain the input stream from urlconnection and construct the datainputstream object
Printstream PS = new printsteam (con. getoutupsteam ());
// Obtain the output stream from urlconnection and construct the printstream object.
String line = dis. Readline (); // read a row from the server
PS. println ("client... "); // Write the string to the server" client... "
Backwards Is the CGI program on the server. In fact, the URL-like method opensteam () is implemented through urlconnection. It is equivalent
Openconnection (). getinputstream ();
URL-based network programming is based on the socket interface at the underlying layer. Standard network services such as WWW and FTP are all based on the TCP protocol, so URL programming is also an application based on TCP in essence.
8.3 socket-based low-level Java Network Programming
8.3.1 socket communication
Two programs on the network exchange data through a two-way communication connection. one end of this two-way link is called a socket. Socket is usually used to connect the customer and the service provider. Socket is a very popular programming interface of TCP/IP protocol. A socket is uniquely identified by an IP address and a port number.
In traditional UNIX environments, there are more than one socket interface that can operate the TCP/IP protocol, and the socket supports not only the TCP/IP protocol, therefore, there is no bound relationship between the two. In the Java environment, socket programming mainly refers to network programming based on TCP/IP protocol.
8.3.2 General socket communication process
The general connection process of using socket for client/server programming is as follows: whether a port of the server listen (listener) has a connection request, and the client sends a connect (connection) to the server) request. The server sends an accept (accept) message back to the client. A connection is established. Both the server and client can communicate with each other by sending, writing, and other methods.
For a fully functional socket, it must contain the following basic structure. The working process includes the following four basic steps:
(1) create a socket;
(2) Open the input/output stream connected to the socket;
(3) perform read/write operations on the socket according to certain protocols;
(4) Disable socket.
8.3.3 create a socket
Java provides two types of socket and serversocket in the java.net package, which are used to represent the client and server for two-way connection respectively. These are two encapsulated classes that are very convenient to use. The construction method is as follows:
Socket (inetaddress address, int port );
Socket (inetaddress address, int port, Boolean stream );
Socket (string host, int prot );
Socket (string host, int Prot, Boolean stream );
Socket (socketimpl impl)
Socket (string host, int port, inetaddress localaddr, int localport)
Socket (inetaddress address, int port, inetaddress localaddr, int localport)
Serversocket (INT port );
Serversocket (INT port, int backlog );
Serversocket (INT port, int backlog, inetaddress bindaddr)
Here, address, host, and port are the IP address, host name, and port number of the other side of the two-way connection. Stream indicates whether the socket is a stream socket or a datagram socket. localport indicates the port number of the local host, localaddr and bindaddr are the addresses of local machines (the host address of serversocket), impl is the parent class of socket, which can be used to create both serversocket and socket. Count indicates the maximum number of connections supported by the server. For example:
Socket Client = new socket ("127.0.01.", 80 );
Serversocket Server = new serversocket (80 );
Note: Be careful when selecting a port. Each port provides a specific service. Only the correct port can be provided to obtain the corresponding service. 0 ~ The port number of 1023 is retained by the system. For example, the port number of the HTTP service is 80, the port number of the Telnet service is 21, and the port number of the FTP service is 23, it is best to select a number greater than 1023 to prevent conflicts.
If an error occurs during socket creation, an ioexception is generated and must be processed in the program. Therefore, exceptions must be caught or thrown when a socket or serversocket is created.
8.3.8 simple Client/Server programming
The following is a demo of a typical C/S structure for customer-server interaction using Socket. The reader carefully reads this program, we will have a deeper understanding of the concepts discussed above. For the significance of the program, see annotations.
1. Client Program
Import java. Io .*;
Import java.net .*;
Public class talkclient {
Public static void main (string ARGs []) {
Try {
Socket socket = new socket ("127.0.0.1", 4700 );
// Send a customer request to port 4700 of the Local Machine
Bufferedreader sin = new bufferedreader (New inputstreamreader (system. In ));
// The bufferedreader object is constructed by the system standard input device.
Printwriter OS = new printwriter (socket. getoutputstream ());
// Obtain the output stream from the socket object and construct the printwriter object
Bufferedreader is = new bufferedreader (New inputstreamreader (socket. getinputstream ()));
// Obtain the input stream from the socket object and construct the corresponding bufferedreader object
String Readline;
Readline = sin. Readline (); // read a string from the system standard input
While (! Readline. Equals ("bye ")){
// If the string read from the standard input is "bye", the loop is stopped.
OS. println (Readline );
// Output the string read from the system standard input to the server
OS. Flush ();
// Refresh the output stream so that the server receives the string immediately
System. Out. println ("client:" + Readline );
// Print the read string on the system standard output
System. Out. println ("server:" + is. Readline ());
// Read a string from the server and print it to the standard output.
Readline = sin. Readline (); // read a string from the system standard input
} // Continue the loop
OS. Close (); // close the socket output stream
Is. Close (); // close the socket input stream
Socket. Close (); // close the socket
} Catch (exception e ){
System. Out. println ("error" + E); // the error message is printed.
}
}
}
2. server programs
Import java. Io .*;
Import java.net .*;
Import java. Applet. Applet;
Public class talkserver {
Public static void main (string ARGs []) {
Try {
Serversocket Server = NULL;
Try {
Server = new serversockets (4700 );
// Create a serversocket to listen to customer requests on port 4700
} Catch (exception e ){
System. Out. println ("can not listen to:" + E );
// Error: print error message
}
Socket socket = NULL;
Try {
Socket = server. Accept ();
// Use accept () to block waiting for customer requests.
// When the request arrives, a socket object is generated and the execution continues.
} Catch (exception e ){
System. Out. println ("error." + E );
// Error: print error message
}
String line;
Bufferedreader is = new bufferedreader (New inputstreamreader (socket. getinputstream ()));
// Obtain the input stream from the socket object and construct the corresponding bufferedreader object
Printwriter OS = newprintwriter (socket. getoutputstream ());
// Obtain the output stream from the socket object and construct the printwriter object
Bufferedreader sin = new bufferedreader (New inputstreamreader (system. In ));
// The bufferedreader object is constructed by the system standard input device.
System. Out. println ("client:" + is. Readline ());
// Print the string read from the client on the standard output
Line = sin. Readline ();
// Read a string from the standard input
While (! Line. Equals ("bye ")){
// If the string is "bye", the loop is stopped.
OS. println (line );
// Output the string to the client
OS. Flush ();
// Refresh the output stream so that the client receives the string immediately
System. Out. println ("server:" + line );
// Print the read string on the system standard output
System. Out. println ("client:" + is. Readline ());
// Read a string from the client and print it to the standard output.
Line = sin. Readline ();
// Read a string from the system standard input
} // Continue the loop
OS. Close (); // close the socket output stream
Is. Close (); // close the socket input stream
Socket. Close (); // close the socket
Server. Close (); // close serversocket
} Catch (exception e ){
System. Out. println ("error:" + E );
// Error: print error message
}
}
}
8.3.9 support multi-Client/Server programming
The client/server program provided above can only implement a conversation between the server and a customer. In practical applications, a permanent program is often run on the server. It can receive requests from multiple other clients and provide corresponding services. In order to provide services to multiple customers on the server side, the above program needs to be transformed to implement multi-client mechanism using multithreading. The server always listens to the customer request on the specified port. Once the customer request is monitored, the server starts a special service thread to respond to the customer's request, the server itself enters the listening status immediately after the thread is started, waiting for the arrival of the next customer.
Serversocket = NULL;
Boolean listening = true;
Try {
Serversocket = new serversocket (4700 );
// Create a serversocket to listen to customer requests on port 4700
} Catch (ioexception e ){}
While (Listening) {// loop listener forever
New serverthread (serversocket. Accept (), clientnum). Start ();
// Listen to the customer request, according to the obtained socket object and
Create and start a service thread
Clientnum ++; // increase the customer count
}
Serversocket. Close (); // close serversocket
Design serverthread class
Public class serverthread extends thread {
Socket socket = NULL; // Save the socket object related to this thread
Int clientnum; // Save the customer count of the current process
Public serverthread (Socket socket, int num) {// Constructor
This. Socket = socket; // initialize the socket variable
Clientnum = num + 1; // initialize the clientnum variable
}
Public void run () {// thread body
Try {// here to receive and send data}
8.3.10 datav Newsletter
As mentioned above, in addition to the TCP protocol, the transport layer of the TCP/IP protocol also has a UDP protocol. Compared with TCP, UDP is not widely used, several standard application layer protocols: HTTP, FTP, SMTP... TCP is used. However, with the development of computer networks, UDP is increasingly showing its power, especially in scenarios requiring strong real-time interaction, such as online games and video conferences, UDP is even more powerful. Next we will introduce how to Implement UDP network transmission in the Java environment.
8.3.11 what is datasync
Similar to the mail system in daily life, data packets cannot be sent reliably. connection-oriented TCP is like a telephone call. Both parties are sure that the other party has received the information. Before this chapter, we have compared UDP and TCP. Here we will give a little more detail:
TCP is reliable and the transmission size is not limited. However, connection establishment time is required, and the error control overhead is high.
UDP is not reliable, and the error control overhead is small. The transmission size is limited to 64 KB and no connection is required.
8.3.12 representation of datax communication: datagramsocket; datagrampacket
The java.net package provides two types of mongoramsocket and mongorampacket to support datagram communication. mongoramsocket is used to establish communication connections for transmitting datagram between programs, and mongorampacket is used to represent a datagram. First, let's take a look at the construction method of datagramsocket:
Datagramsocket ();
Datagramsocket (INT prot );
Datagramsocket (INT port, inetaddress laddr)
The port indicates the port number used by the socket. If the port number is not specified, connect the socket to an available port on the local host. Laddr indicates an available local address. Make sure that no port conflict occurs when the port number is given. Otherwise, exceptions of the socketexception class will be generated. Note: Both of the preceding constructor Methods declare that socketexception is not the exception during running, and must be processed in the program, captured, or declared.
When you write a client/server program in the datagram mode, you must first create an initramsocket object to receive or send a datagram, then, the initrampacket class object is used as the carrier for data transmission. Let's take a look at the constructor of datagrampacket:
Datagrampacket (byte Buf [], int length );
Datagrampacket (byte Buf [], int length, inetaddress ADDR, int port );
Datagrampacket (byte [] Buf, int offset, int length );
Datagrampacket (byte [] Buf, int offset, int length, inetaddress address, int port );
The Buf stores the datagram data. The length is the length of the data in the datagram, And the ADDR and port specify the destination address. The offset indicates the amount of data in the datagram.
Before receiving data, use the first method above to generate a mongorampacket object and provide the buffer and length of the received data. Then call the assumramsocket method receive () to wait for the arrival of the datagram, and receive () will wait until a datagram is received.
Datagrampacket packet = new datagrampacket (BUF, 256 );
Socket. Receive (packet );
Before sending data, you need to create a new initrampacket object. In this case, you need to use the second constructor method above, while giving a buffer for storing the sent data, the complete destination address, including the IP address and port number, is also provided. Data is sent through the mongoramsocket Method Send (). Send () searches for the path based on the destination address of the datagram to transmit the datagram.
Datagrampacket packet = new datagrampacket (BUF, length, address, Port );
Socket. Send (packet );
When constructing a Data Report, The inetaddress class parameter is required. The class inetaddress is defined in the java.net package to indicate an Internet address. We can use the class method getbyname () provided by it to obtain the IP address of the host from a string that represents the host name, then obtain the corresponding address information.
8.3.14 Broadcast Communication Using Datagram
Datagramsocket only allows a datagram to send a destination address. The java.net package provides a multicastsocket class that allows data to be broadcast to all customers on the port. Multicastsocket is used on the client to listen to data broadcast by the server.
This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/coolriver/archive/2004/09/13/102420.aspx
Note: This guy liked to write comments under the code, and I was so disgusted. Dizzy ......