1. Two main problems in network programming
One is how to accurately locate one or more hosts on the network, and the other is how to reliably and efficiently transmit data after finding the host.
In the TCP/IP protocol, the IP layer is mainly responsible for the location of the network host and the routing of data transmission. The IP address can uniquely determine a host on the Internet.
The TCP layer provides a reliable (tcp) or non-reliable (UDP) data transmission mechanism for application, which is the main object of network programming, and generally does not need to care about how the IP layer processes data.
The most popular network programming model at present is the client/server (C/S) structure. That is, one of the communication parties acts as a server to wait for the customer to submit a request and respond. The customer applies to the server when the service is needed. The server is generally always running as a daemon, listening to the network port. Once a customer requests it, it will start a service process to respond to the customer, and at the same time continue to listen to the service port itself so that later customers can also get service in a timely manner.
2. Two types of transmission protocols: TCP; UDP
TCP is the abbreviation of Tranfer Control Protocol , a connection-oriented protocol that ensures reliable transmission. Transmission through TCP protocol results in an order of error-free data streams. A connection must be established between the two pairs of sockets of the sender and the receiver in order to communicate on the basis of the TCP protocol. When one socket (usually a server socket) is waiting to establish a connection, the other socket can require a connection. Once these two sockets are connected, they can perform two-way data transmission, and both parties can perform sending or receiving operations.
UDP is the abbreviation of User Datagram Protocol . It is a connectionless protocol. Each datagram is an independent information, including a complete source or destination address. It is transmitted to the destination on the network by any possible path. Therefore, whether it can reach the destination, the time to reach the destination, and the correctness of the content cannot be guaranteed.
Compare:
UDP:
TCP:
application:
3. Socket-based Java network programming
1. What is Socket
Two programs on the network realize data exchange through a two-way communication connection. One end of this two-way link is called a Socket. Socket is usually used to connect between customers and service providers. Socket is a very popular programming interface of the TCP/IP protocol. A Socket is uniquely determined by an IP address and a port number.
However, the types of protocols supported by Socket are not only TCP/IP, so there is no necessary connection between the two. In the Java environment, Socket programming mainly refers to network programming based on the TCP/IP protocol.
2. The process of Socket communication
The Server side Listen (listens) whether there is a connection request on a certain port. The Client side issues a Connect request to the Server side, and the Server side sends an Accept message back to the Client side. A connection is established. Both the Server and Client side can communicate with each other through Send, Write and other methods.
For a fully functional Socket, it must include the following basic structure, and its working process includes the following four basic steps:
(1) Create Socket;
(2) Open the input/outflow connected to the Socket;
(3) Read/write the Socket according to a certain protocol;
(4) Close Socket. (In actual applications, the displayed close is not used. Although many articles recommend this, in my program, it may not have any impact because the program itself is relatively simple and has low requirements.)
3. Create Socket
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) where address, host and port are the IP address, host name and port number of the other party in the bidirectional connection respectively. The 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 address of the local machine (the host address of the ServerSocket). impl is the socket's parent class, which can be used to create serverSocket and create sockets. count represents the maximum number of connections that the server can support. For example: Learning Video Network http://www.xxspw.com Socket client = new Socket("127.0.01.", 80); ServerSocket server = new ServerSocket(80);Note that you must be careful when selecting a port. Each port provides a specific service. Only by giving the correct port can the corresponding service be obtained. The port numbers from 0~1023 are reserved 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. Therefore, when we select the port number, it is best to choose a number greater than 1023 to prevent conflicts.
If an error occurs when creating a socket, an IOException will be generated and it must be processed in the program. So when creating Socket or ServerSocket, exceptions must be caught or thrown.
4. Simple Client/Server program
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 client request to the 4700 port of the machine BufferedReader sin=new BufferedReader(new InputStreamReader(System.in)); //Construct the BufferedReader object from the system standard input device PrintWriter os=new PrintWriter(socket.getOutputStream()); //Get the output stream from the Socket object and construct the PrintWriter object BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream())); //Get 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", stop the loop os.println(readline); //Output the string read from the system standard input to Server os.flush(); //Refresh the output stream so that the Server immediately receives the string System.out.println("Client:"+readline); //Print the read string 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 to loop os.close(); //Close Socket output stream is.close(); //Close Socket input stream socket.close(); //Close Socket }catch(Exception e) { System.out.println("Error"+e); //An error occurs, an error message is printed} }}2. Server-side program
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 ServerSocket(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 and wait for the client request. If a client //After the request comes, a Socket object is generated and continue to execute } catch(Exception e) { System.out.println("Error."+e); //An error occurs, print error information is printed} String line; BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream())); //Get the input stream from the Socket object and construct the corresponding BufferedReader object PrintWriter os=newPrintWriter(socket.getOutputStream()); //Get the output stream from the Socket object and construct the PrintWriter object BufferedReader sin=new BufferedReader(new InputStreamReader(System.in)); //Construct the BufferedReader object 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", stop the loop os.println(line); //Output the string os.flush() to the client; //Refresh the output stream so that the Client immediately receives the string System.out.println("Server:"+line); //Print the read string 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 to loop os.close(); //Close Socket output stream is.close(); //Close Socket input stream socket.close(); //Close Socket server.close(); //Close ServerSocket }catch(Exception e){ System.out.println("Error:"+e); //An error occurred, print error message} } }5. Support multi-client client/server program
The previous Client/Server program can only implement conversations between Server and one customer. In actual applications, a permanent program is often run on the server, which can receive requests from multiple other clients and provide corresponding services. In order to realize the function of providing services to multiple customers on the server, the above program needs to be transformed and the multi-threading mechanism is implemented. The server always listens to whether there are client requests on the specified port. Once the client request is heard, the server will start a special service thread to respond to the client's request. The server itself immediately enters the listening state after starting the thread, waiting for the next client to arrive.