java network programming
1.1 general
Global village: you are in Xi'an, you are an American friend! How do you communicate with each other?
1.11 take a chestnut for sending letters
The address of the other party, and the other party's information is located to a specific individual. Own address, own information
With the above elements, regardless of the external environment, this letter can theoretically be sent to the other party.
What if we consider the external environment?
1.12 definition of computer network
A computer network system that connects multiple computers with independent functions in different geographical locations and their external devices through communication lines to realize resource sharing and information transmission under the management and coordination of network operating system, network management software and network communication protocol.
1.13 purpose of network programming
Communication, information exchange, data exchange, communication (all the same meaning)
1.14 what is needed to achieve this effect?
1. How to accurately locate a host on the network
Address: port number is as follows
192.168.16.124: 8080
Locate a program on this computer
2. If you find a program on this host, how do you transfer data?
Network programming: TCP/IP protocol C/S architecture
1.2 elements of network communication
How to realize network communication?
Address of both parties:
iP
end slogan
192.168.16.124:5900
Rules: protocols for network communication
TCP/IP
Summary:
1. There are two main problems in network programming
how to accurately locate one or more hosts on the network
how to communicate after finding the host
2. Elements in network programming
IP and port number
network communication protocol UDP,TCP
3. Everything is an object
1.3 IP address
1.31 classes about ip addresses in Java
InetAddress
1.32 a key address:
Local address: 127.0.0.1 and localhost
Query ip address practice code
package com.kuang.lession01; import java.net.InetAddress; import java.net.UnknownHostException; //Remember that the class names are the same, otherwise an error will be reported public class TestInetAddress { public static void main(String[] args) { try { //Query local address InetAddress inetAddress1=InetAddress.getByName("127.0.0.1"); System.out.println(inetAddress1); InetAddress inetAddress3=InetAddress.getByName("localhost"); System.out.println(inetAddress3); InetAddress inetAddress4=InetAddress.getLocalHost(); System.out.println(inetAddress4); //Query network ip address InetAddress inetAddress2=InetAddress.getByName("www.baidu.com");//If you enter a domain name, it will return the ip address corresponding to the domain name System.out.println(inetAddress2); //common method System.out.println(inetAddress2.getAddress());//Freshman address System.out.println(inetAddress2.getCanonicalHostName());//Canonical name System.out.println(inetAddress2.getHostAddress());//ip System.out.println(inetAddress2.getHostName());//Domain name or computer name } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
1.33 ip address classification
Ipv4/ipv6
IPv4 consists of 127.0.0.1 and 4 bytes. 0 ~ 25.542 billion, 3 billion in North America and 400 million in Asia
IPV6:128 bit 8 unsigned integers! For example, 2001: obb2:aaaa:0015:0000:0000:1aaa:1312
public network (Internet) – private network (LAN)
• ABCD class address
192.168.xx.xx for internal use of the organization
Little knowledge: domain names are for easy memory. Each domain name corresponds to an IP address. The computer recognizes the IP address mapped by the domain name and performs the operation.
1.4 ports
1.41 port indicates the process of a program on the computer
different processes have different port numbers! Used to distinguish software!
specified port number range: 0 ~ 65535
the port numbers of different TCP/UDP protocols can be the same: TCP/UDP:65535*2 tcp:80 udp:80, which is OK
However, under a single protocol, port numbers cannot conflict
1.42 port classification
Public port 0 ~ 1024
HTTP:80
HTTPS:443
FTP:21
Telent:23
Program registration port: 1024 - 49151, which is assigned to users or programs
Tomcat:8080
MySQL:3306
Oracle:1521
Dynamic and private: 49152 ~ 65535
1.43 query port practice
netstat -ano / / view all ports
netstat -ano|findstr "5353" view the specified port
Note: make sure there are 5353 in all ports, or you may have retrieved a lonely port
tasklist|findstr "20568" view the process of the specified port
Note: make sure that the port has a corresponding process
The confirmation method is as follows:
Ctrl+shift+ESC opens the task manager
little knowledge: by modifying hosts C:\Windows\System32\drivers\etc\hosts, you can directly modify the mapping name of 127.0.0.1hostsname
Small practice of network address
Be slightly familiar with the usage of InetSocketAddress class in java
package com.kuang.lession01; import java.net.InetSocketAddress; public class TestInetSockeAddress { public static void main(String[] args) { // TODO Auto-generated method stub InetSocketAddress socketAddress=new InetSocketAddress("127.0.0.1",8080); InetSocketAddress socketAddress1=new InetSocketAddress("localhost",8080); System.out.println(socketAddress); System.out.println(socketAddress1); System.out.println(socketAddress.getAddress()); System.out.println(socketAddress.getPort());//port System.out.println(socketAddress.getHostName());//address } }
1.5 communication protocol
Agreement: the agreement is like we speak Mandarin and write Chinese characters now. You can understand it. If I draw in Spanish, you may not understand it, let alone communicate
Network communication protocol: rate, transmission code rate, code structure, transmission control
Two important agreements:
TCP: user transport protocol
UDP: User Datagram Protocol
TCP UDP comparison
TCP
- The destination connection is stable
- Connected triple handshake
- Four disconnected waves
Connect at least three times to ensure a stable connection! Disconnect at least four times to stably disconnect!
Three handshakes for connection: A: request connection, B agree connection and AB connection
Four waves of disconnection: A: request disconnection B: agree disconnection B: disconnect, a: disconnect
UDP
- No connection established and unstable
- Client, server: there is no clear boundary
- It can be sent to you whether it is ready or not
- DDOS saturation attack
TCP program practice
The following is a remote chat program implemented according to the network programming principle of java.
client
- Connect to the server Socket
- send message
package lesson02; //client import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; //client public class TcpClientDemo01 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc =new Scanner(System.in); System.out.println("Please enter the text you want to send to the server:"); while(true) { Socket socket=null; //Expand the scope of Socket and OutpytStream to facilitate the final solution of exception throwing OutputStream os=null; String str =sc.next(); try {//core //1. Know the address and port number of the server InetAddress serverIP=InetAddress.getByName("127.0.0.1"); int port = 9921; //2. Create a socket connection socket=new Socket(serverIP, port); //3. Send message IO stream os=socket.getOutputStream(); os.write(str.getBytes()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { /* * Close exception the following is the basic template for large companies to solve exceptions */ if(os!=null) { try { os.close(); } catch (IOException e2) { // TODO: handle exception } } if(socket!=null) { try { socket.close(); } catch (IOException e2) { // TODO: handle exception } } } } } }
The server
- Establish service port ServerSocket
- Wait for user's link accept
- Accept user messages
package lesson02; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; //Server public class TcpServerDemo01 { public static void main(String[] args) { ServerSocket serverSocket=null; Socket socket=null; InputStream is =null; ByteArrayOutputStream baos=null; try { //1. Create a new address serverSocket=new ServerSocket(9921); while(true) { //2. Wait for the client to connect socket=serverSocket.accept(); //3. Read the message from the client is =socket.getInputStream(); //Connect the input stream through a pipe //Pipe flow baos=new ByteArrayOutputStream();//Output to console byte[]buffer=new byte[1024]; int len; while((len=is.read(buffer))!=-1) {//When there is no end, the content is written to Bao baos.write(buffer,0,len); } System.out.println(baos.toString()); //output } } catch (IOException e) { // TODO Auto-generated catch block //close e.printStackTrace(); }finally { //close resource if(baos!=null) { try { baos.close(); } catch (IOException e2) { // TODO: handle exception } } if(is!=null) { try { is.close(); } catch (IOException e2) { // TODO: handle exception } } if(socket!=null) { try { socket.close(); } catch (IOException e2) { // TODO: handle exception } } if(serverSocket!=null) { try { serverSocket.close(); } catch (IOException e2) { // TODO: handle exception } } } } }
Note: 1. How does eclipse run on multiple consoles?
You can see this blog:
2. bind: address already in use encountered
What should I do?
Solution: you can read this blog