Java is a high-level programming language launched by Sun Microsystems in May 1995. Java can run on multiple platforms, such as Windows, Mac OS, and other UNIX versions of systems. As a representative of static object-oriented programming languages, Java language perfectly implements object-oriented theory and allows programmers to perform complex programming with an elegant way of thinking. "Geek Academy Java Video Tutorial" will take you into the Java language world from shallow to deep, from basic to advanced.
Course playback address: http://www.php.cn/course/275.html
The teacher’s teaching style:
The teacher’s lectures are simple, clear, layer-by-layer analysis, interlocking, rigorous argumentation, rigorous structure, and use the logical power of thinking to attract students’ attention Strength, use reason to control the classroom teaching process. By listening to the teacher's lectures, students not only learn knowledge, but also receive thinking training, and are also influenced and influenced by the teacher's rigorous academic attitude
The more difficult point in this video is Socket communication in Java :
First, there are two main problems in network programming
One is how to accurately locate one or more computers on the network 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 positioning of network hosts and routing of data transmission. A host on the Internet can be uniquely determined by the IP address.
The TCP layer provides application-oriented reliable (tcp) or unreliable (UDP) data transmission mechanisms. This is the main object of network programming. Generally, you do not need to care about how the IP layer processes data.
The currently more popular network programming model is the client/server (C/S) structure. That is, one of the communication parties acts as a server and waits for the client to make a request and respond. Customers apply to the server when they need services. The server generally always runs as a daemon process, listening to the network port. Once there is a customer request, it will start a service process to respond to the customer, and at the same time continue to monitor the service port so that subsequent customers can receive services in time.
Second, two types of transmission protocols: TCP; UDP
TCP is the abbreviation of Transfer Control Protocol, which is a connection-oriented protocol that ensures reliable transmission. Transmitted through the TCP protocol, a sequential, error-free data stream is obtained. A connection must be established between the two sockets of the sender and the receiver in order to communicate based on the TCP protocol. When one socket (usually a server socket) is waiting to establish a connection, the other socket can request that a connection be established. 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 piece of information, including the complete source address or destination address. It is transmitted on the network in any possible way. The path is transmitted to the destination, so whether the destination can be reached, the time to reach the destination, and the correctness of the content cannot be guaranteed.
Comparison:
UDP: 1, complete address information is given in each datagram, so there is no need to establish a connection between the sender and the receiver.
2. There is a size limit when UDP transmits data. Each transmitted datagram must be limited to 64KB.
3. UDP is an unreliable protocol. Datagrams sent by the sender do not necessarily arrive at the receiver in the same order.
TCP: 1. Connection-oriented protocol, in socket A connection must be established before data transmission between two parties, so connection time is required in TCP.
2. TCP transmission data size limit. Once the connection is established, the sockets of both parties can transmit large
3. TCP is a reliable protocol, which ensures that the receiver obtains all the data sent by the sender completely and correctly.
Application:
1. TCP has a strong vitality in network communication. For example, remote connection (Telnet) and file transfer (FTP) require data of variable length to be transmitted reliably. However, reliable transmission comes at a price. Checking the correctness of the data content will inevitably take up computer processing time and network bandwidth. Therefore, TCP transmission is not as efficient as UDP.
2. UDP is simple to operate and requires less supervision, so it is usually used for client/server applications in distributed systems with high reliability in local area networks. For example, the video conferencing system does not require the audio and video data to be absolutely correct, as long as the continuity is ensured. In this case, it is obviously more reasonable to use UDP.
3. Java network programming based on Socket
1. What is Socket
Two programs on the network realize the exchange of data through a two-way communication connection. This two-way One end of the link is called a Socket. Socket is usually used to realize the connection between the client and the server. Socket is a very popular programming interface for the TCP/IP protocol. A Socket is uniquely determined by an IP address and a port number.
However, the protocol types 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, Socket communication process
The server side listens (monitors) whether there is a connection request on a certain port. The client side sends a Connect (connection) request to the server side, and the server side sends a connection request to the client side. Return Accept message. A connection is established. Both the Server side and the Client side can communicate with each other through methods such as Send and Write.
For a fully functional Socket, it must contain the following basic structure, and its working process includes the following four basic steps:
(1) Create Socket;
( 2) Open the input/output stream connected to the Socket;
(3) Perform read/write operations on the Socket according to a certain protocol;
(4) Close the Socket. (In practical applications , the displayed close is not used, although many articles recommend this, but in my program, it may not have any impact because the program itself is relatively simple and the requirements are not high)
3, Create Socket
Create Socket
java provides two classes, Socket and ServerSocket, in the package java.NET, which are used to represent the client and server of two-way connections respectively. These are two very well-encapsulated classes and are very convenient to use. Its 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)
Where address, host and port are the IP address, host name and port number of the other party in the two-way connection respectively, stream indicates whether the socket is a stream socket or a datagram socket, and localPort indicates the local host. The port number, localAddr and bindAddr are the address of the local machine (the host address of ServerSocket), and impl is the parent class of socket, which can be used to create both serverSocket and Socket. count represents the maximum number of connections that the server can support. For example: Learning Video Network http://www.php.cn
Socket client = new Socket("127.0.01.", 80); ServerSocket server = new ServerSocket(80);
Note that you must be careful when selecting the port. Each port provides a specific service. Only by giving the correct port can you obtain the corresponding service. Port numbers from 0 to 1023 are reserved by the system. For example, the port number for http service is 80, the port number for telnet service is 21, and the port number for ftp service is 23. Therefore, when we choose a port number, it is best to choose a port number greater than 1023. number to prevent conflicts.
If an error occurs when creating a socket, an IOException will be generated, which must be handled in the program. So when creating a Socket or ServerSocket, you must catch or throw an exception.
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); //向本机的4700端口发出客户请求 BufferedReader sin=new BufferedReader(new InputStreamReader(System.in)); //由系统标准输入设备构造BufferedReader对象 PrintWriter os=new PrintWriter(socket.getOutputStream()); //由Socket对象得到输出流,并构造PrintWriter对象 BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream())); //由Socket对象得到输入流,并构造相应的BufferedReader对象 String readline; readline=sin.readLine(); //从系统标准输入读入一字符串 while(!readline.equals("bye")){ //若从标准输入读入的字符串为 "bye"则停止循环 os.println(readline); //将从系统标准输入读入的字符串输出到Server os.flush(); //刷新输出流,使Server马上收到该字符串 System.out.println("Client:"+readline); //在系统标准输出上打印读入的字符串 System.out.println("Server:"+is.readLine()); //从Server读入一字符串,并打印到标准输出上 readline=sin.readLine(); //从系统标准输入读入一字符串 } //继续循环 os.close(); //关闭Socket输出流 is.close(); //关闭Socket输入流 socket.close(); //关闭Socket }catch(Exception e) { System.out.println("Error"+e); //出错,则打印出错信息 } } }
2. Server 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); //创建一个ServerSocket在端口4700监听客户请求 }catch(Exception e) { System.out.println("can not listen to:"+e); //出错,打印出错信息 } Socket socket=null; try{ socket=server.accept(); //使用accept()阻塞等待客户请求,有客户 //请求到来则产生一个Socket对象,并继续执行 }catch(Exception e) { System.out.println("Error."+e); //出错,打印出错信息 } String line; BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream())); //由Socket对象得到输入流,并构造相应的BufferedReader对象 PrintWriter os=newPrintWriter(socket.getOutputStream()); //由Socket对象得到输出流,并构造PrintWriter对象 BufferedReader sin=new BufferedReader(new InputStreamReader(System.in)); //由系统标准输入设备构造BufferedReader对象 System.out.println("Client:"+is.readLine()); //在标准输出上打印从客户端读入的字符串 line=sin.readLine(); //从标准输入读入一字符串 while(!line.equals("bye")){ //如果该字符串为 "bye",则停止循环 os.println(line); //向客户端输出该字符串 os.flush(); //刷新输出流,使Client马上收到该字符串 System.out.println("Server:"+line); //在系统标准输出上打印读入的字符串 System.out.println("Client:"+is.readLine()); //从Client读入一字符串,并打印到标准输出上 line=sin.readLine(); //从系统标准输入读入一字符串 } //继续循环 os.close(); //关闭Socket输出流 is.close(); //关闭Socket输入流 socket.close(); //关闭Socket server.close(); //关闭ServerSocket }catch(Exception e){ System.out.println("Error:"+e); //出错,打印出错信息 } } }
5, supports multiple clients client/server program
The previous Client/Server program can only realize the dialogue between the Server and one client. In practical 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 clients on the server side, the above program needs to be modified and multi-threading is used to implement the multi-client mechanism. The server always monitors whether there are customer requests on the designated port. Once a customer request is monitored, the server will start a special service thread to respond to the customer's request, and the server itself will enter the listening state immediately after starting the thread. Waiting for the next customer to arrive.
The above is the detailed content of Geek Academy Java video tutorial resource sharing. For more information, please follow other related articles on the PHP Chinese website!