Network programming
1. Overview
-
Computer network:
- Computer network refers to a computer system that connects multiple computers and their external devices with independent functions in different geographical locations through communication lines (linear and wireless), and realizes resource sharing and information transmission under the management and coordination of network operating system, network management software and network communication protocol.
-
Purpose of network programming:
- Dissemination and exchange of information, data exchange and communication.
-
What is needed to achieve this effect:
- How to accurately locate a host 192.168.1.100: port on the network and locate a resource on the computer.
- After finding the host, how to transmit data?
-
JavaWeb: Web programming B/S architecture (Browser / server)
-
Network programming: TCP/IP C/S architecture (client / server)
2. Elements of network communication
-
How to realize network communication?
-
Address of both parties:
- IP
- Port number
- 192.168.16.124:5900
-
Rules: protocols for network communication
TCP/IP reference model:
-
Summary:
-
Two main problems in network programming
- How to accurately locate one or more hosts on the network
- How to communicate after finding the host
-
Elements in network programming
- IP and port numbers
- Network communication protocol udp,tcp
-
Everything is object
-
3 ,IP
-
ip address: InetAddress
-
Uniquely locate a computer on a network
-
127.0.0.1: local localhost
-
Classification of ip addresses
-
IPV4/IPv6
-
IPv4: 127.0.0.1, composed of 4 bytes, 0-255, 4.2 billion; 3 billion are in North America and 400 million in Asia, which were exhausted in 2011
-
IPV6: 128 bit. 8 unsigned integers!
2001;Obb2;aaaa;0015;0000;0000;1aaa;1312
-
-
Public network (Internet) - private network (LAN)
- ABCD class address
- 192.168.xx.xx, specially for internal use of the organization
-
-
Domain name: memory IP problem!
- IP: www.vip.com
package com.lesson01; import java.net.InetAddress; import java.net.UnknownHostException; //Test Ip public class TestInetAddress { public static void main(String[] args) { try { //Query local address InetAddress inetAddress01 = InetAddress.getByName("127.0.0.1"); System.out.println(inetAddress01); InetAddress inetAddress03 = InetAddress.getByName("localhost"); System.out.println(inetAddress03); InetAddress inetAddress04 = InetAddress.getLocalHost(); System.out.println(inetAddress04); //Query website IP address InetAddress inetAddress02 = InetAddress.getByName("www.baidu.com"); System.out.println(inetAddress02); //common method // System.out.println(inetAddress02.getAddress()); System.out.println(inetAddress02.getCanonicalHostName());//Canonical name System.out.println(inetAddress02.getHostAddress());//ip System.out.println(inetAddress02.getHostName());//Domain name, or the name of your computer } catch (UnknownHostException e) { e.printStackTrace(); } } }
4. Port
-
A port represents the process of a program on a computer
-
Different processes have different port numbers! Used to distinguish software!
-
The port is specified as: 0-65535
-
TCP, UDP: 0-65535 * 2. Port numbers cannot conflict under a single protocol.
-
Port classification
-
Total ports 0-1023
- HTTP : 80
- HTTPS : 443
- FTP : 21
- Telet : 23
-
Program registration port: 1024 - 49151, assigned to users or programs
- Tomcat: 8080
- Mysql: 3306
- Oracle: 1521
-
Dynamic, private: 49152-65535
-
netstat -ano #View all ports netstat -ano | findstr "5900" #View the specified port tasklist | findstr "8696" #View processes on the specified port Ctrl + Shift + ESC #Task manager shortcuts
package com.lesson01; import java.net.InetSocketAddress; public class TextInetSocketAddress { public static void main(String[] args) { InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1",8080); InetSocketAddress socketAddress02 = new InetSocketAddress("localhost",8080); System.out.println(socketAddress); System.out.println(socketAddress02); System.out.println(socketAddress.getAddress()); System.out.println(socketAddress.getHostName());//address System.out.println(socketAddress.getPort());//port } }
- schematic diagram
5. Communication protocol
-
Agreement: agreement, just as we speak Mandarin now.
-
Network communication protocol: rate, transmission code rate, code structure, transmission control
-
Question: very complex?
Big event flower: layered!
-
TCP/IP protocol cluster: it is actually a group of protocols
-
important
- TCP: user transport protocol
- UDP: User Datagram Protocol
-
Famous agreement:
- TCP:
- IP: network interconnection protocol
-
Comparison between TCP and UDP:
-
TCP: call
-
Connection: stable
-
Three handshakes and four waves
Three handshakes: At least three times to ensure a stable connection! A: What are you worried about? B: What do you think? A: Do it once Four waves: A: I am afraid that l have to go! B: Are you really leaving? B: Are you really leaving? A: I really have to go!
-
Client, server
-
The transmission is completed, the connection is released, and the efficiency is low
-
-
UDP: send SMS
- Not connected, unstable
- Client and server: there is no clear boundary
- Ready or not, it can be sent to you
- Missile
- DDOS: flood attack! (saturation attack)
-
-
Schematic diagram of triple Handshake:
6 ,TCP
TCP chat
- client
- Connect to the server Socket
- send message
package com.lesson02; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; //client public class TcpClientDemo01 { public static void main(String[] args) { Socket socket = null; OutputStream os = null; try { //1. Know the address and port number of the server InetAddress serverIP = InetAddress.getByName("127.0.0.1"); int port = 9999; //2. Create a socket connection socket = new Socket(serverIP,port); //3. Send message IO stream os = socket.getOutputStream(); os.write("Hello, welcome to learn Crazy God said Java".getBytes()); } catch (Exception e) { e.printStackTrace(); }finally { if (os!=null){ try { os.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket!=null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
- The server
- Establish service port ServerSocket
- Wait for the user's connection accept
- Receive user information
package com.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. I want to have an address serverSocket = new ServerSocket(9999); while (true){ //2. Wait for the client to connect socket = serverSocket.accept(); //3. Read the message from the client is = socket.getInputStream(); /* byte[] buffer = new byte[1024]; int len; while((len=is.read(buffer))!=-1){ String msg = new String(buffer,0,len); System.out.println(msg); } */ //Pipe flow baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while((len=is.read(buffer))!=-1){ baos.write(buffer,0,len); } System.out.println(baos.toString()); } } catch (IOException e) { e.printStackTrace(); }finally { //close resource if (baos!=null){ try { baos.close(); } catch (IOException e) { e.printStackTrace(); } } if (is!=null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket!=null){ try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } if (serverSocket!=null){ try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
- Schematic diagram of pipeline flow
TCP file upload implementation
- Server
package com.lesson02; import java.io.*; import java.net.InetAddress; import java.net.Socket; public class TcpClientDemo02 { public static void main(String[] args) throws Exception{ //1. Create a Socket connection Socket socket = new Socket(InetAddress.getByName("127.0.0.1"),9000); //2. Create an output stream OutputStream os = socket.getOutputStream(); //3. Read file FileInputStream fis = new FileInputStream("we.png"); //4. Write out the document byte[] buffer = new byte[1024]; int len; while ((len=fis.read(buffer))!=-1){ os.write(buffer,0,len); } //Notify the server that I'm finished. Or you're reading yourself. socket.shutdownOutput();//I've played! //Make sure that the server has received it before you can disconnect InputStream inputStream = socket.getInputStream(); //Pipe flow ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer2 = new byte[1024]; int len2; while ((len2=inputStream.read(buffer2))!=-1){ baos.write(buffer2,0,len2); } System.out.println(baos.toString()); //5. Close resources baos.close(); inputStream.close(); fis.close(); os.close(); socket.close(); } }
- client
package com.lesson02; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class TcpServerDeom02 { public static void main(String[] args) throws Exception{ //1. Create service ServerSocket serverSocket = new ServerSocket(9000); //2. Listen for client connections Socket socket = serverSocket.accept();//Blocking listening, waiting for the client to connect //3. Get input stream InputStream is = socket.getInputStream(); //4. File output FileOutputStream fos = new FileOutputStream("receice.png"); byte[] buffer = new byte[1024]; int len; while ((len=is.read(buffer))!=-1){ fos.write(buffer,0,len); } //Notify the client that I have received it OutputStream os = socket.getOutputStream(); os.write("I'm done. You can disconnect".getBytes()); //close fos.close(); is.close(); socket.close(); serverSocket.close(); } }
Tomcat
- Server
- Custom S
- Tomcat server S. Java background development!
- client
- Custom C
- Browser B
- start.bat in the bin directory under the Tomcat package starts tomcat, and shutdown closes Tomcat.
- After startup, check localhost: 8080 on the web page to see whether the startup is successful. Launch success page:
- webapps package the following is the development package of the web page. The web page can be modified.
- If the console is garbled, you can change UTF-8 to GBK in the logging.properties file in conf.
- If the file is garbled when the web page is opened, you can modify the encoding method of the file.
- Experience the feeling that the port is occupied!
7 ,UDP
UDP message sending
- Texting: no connection, need to know each other's address!
- Send message:
package com.lesson03; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; //No connection to the server is required public class UdpClientDemo01 { public static void main(String[] args) throws Exception { //1. Create a Socket DatagramSocket socket= new DatagramSocket(); //2. Build a package String msg = "Hello, server!"; InetAddress localhost = InetAddress.getByName("localhost"); int port = 9090; //Data, starting from the length of the data, to whom DatagramPacket packet = new DatagramPacket(msg.getBytes(),0,msg.getBytes().length,localhost,port); //3. Send packet socket.send(packet); //4. Close the flow socket.close(); } }
- receiving end
package com.lesson03; import java.net.DatagramPacket; import java.net.DatagramSocket; //Or wait for the client to connect! public class UdpServerDemo01 { public static void main(String[] args) throws Exception{ //Open port DatagramSocket socket = new DatagramSocket(9090); //Receive packet byte[] buffer = new byte[1024]; DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length); socket.receive(packet);//Blocking reception System.out.println(packet.getAddress().getHostAddress()); System.out.println(new String(packet.getData(),0,packet.getLength())); } }
UDP chat implementation
package com.chat; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; public class UdpSenderDemo01 { public static void main(String[] args) throws Exception { DatagramSocket socket = new DatagramSocket(8888); //Prepare data: the console reads System.in BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true){ String data = reader.readLine(); byte[] datas = data.getBytes(); DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",6666)); socket.send(packet); if (data.equals("bye")){ break; } } socket.close(); } }
package com.chat; import java.net.DatagramPacket; import java.net.DatagramSocket; public class UdpReceiveDemo01 { public static void main(String[] args) throws Exception{ DatagramSocket socket = new DatagramSocket(6666); while (true){ //Ready to receive package byte[] container = new byte[1024]; DatagramPacket packet = new DatagramPacket(container,0,container.length); socket.receive(packet);//Blocking receiving package //Disconnect bye byte[] data =packet.getData(); String receiveData = new String(data,0,data.length); System.out.println(receiveData); if (receiveData.equals("bye")){ break; } } socket.close(); } }
UDP multithreading online consultation
- Online consultation: both can be the sender and the receiver!
package com.chat; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; public class TalkSend implements Runnable { DatagramSocket socket = null; BufferedReader reader = null; private int fromport; private String toIP; private int toPort; public TalkSend(int fromport, String toIP, int toPort) { this.fromport = fromport; this.toIP = toIP; this.toPort = toPort; try { socket = new DatagramSocket(fromport); reader = new BufferedReader(new InputStreamReader(System.in)); } catch (Exception e) { e.printStackTrace(); } } @Override public void run() { while (true){ try { String data = reader.readLine(); byte[] datas = data.getBytes(); DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress(this.toIP,this.toPort)); socket.send(packet); if (data.equals("bye")){ break; } } catch (IOException e) { e.printStackTrace(); } } socket.close(); } }
package com.chat; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class TalkReceive implements Runnable { DatagramSocket socket = null; private int port; private String msgFrom; public TalkReceive(int port,String msgFrom) { this.port = port; this.msgFrom = msgFrom; try { socket = new DatagramSocket(port); } catch (SocketException e) { e.printStackTrace(); } } @Override public void run() { while (true){ try { //Ready to receive package byte[] container = new byte[1024]; DatagramPacket packet = new DatagramPacket(container,0,container.length); socket.receive(packet);//Blocking receiving package //Disconnect bye byte[] data =packet.getData(); String receiveData = new String(data,0,data.length); System.out.println(msgFrom+":"+receiveData); if (receiveData.equals("bye")){ break; } } catch (IOException e) { e.printStackTrace(); } } socket.close(); } }
package com.chat; public class TalkStudent { public static void main(String[] args) { //Open two threads new Thread(new TalkSend(7777,"localhost",9999)).start();//Just fill in fromport. new Thread(new TalkReceive(8888,"teacher")).start(); } }
package com.chat; public class TalkTeacher { public static void main(String[] args) { new Thread(new TalkSend(5555,"localhost",8888)).start(); new Thread(new TalkReceive(9999,"student")).start(); } }
8,URL
https://www.baidu.com/
Uniform resource locator: used to locate a resource on the Internet
DNS: domain name resolution www.baidu.com xxx.x... x... x
agreement://ip address: port / project name / resource
package com.lesson04; import java.net.MalformedURLException; import java.net.URL; public class URLDemo01 { public static void main(String[] args) throws MalformedURLException { URL url = new URL("http://localhost:8080/helloworld/index.jsp?username=kuangshen&password=123"); System.out.println(url.getProtocol());//agreement System.out.println(url.getHost());//Host IP System.out.println(url.getPort());//port System.out.println(url.getPath());//file System.out.println(url.getFile());//Full path System.out.println(url.getQuery());//parameter } }
- URL to download network resources
package com.lesson04; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; public class URLDown { //A new txt file is created in the tomcat package. You must run tomcat to download it. public static void main(String[] args) throws Exception{ //1. Download address URL url = new URL("http://localhost:8080/wangcheng/SecurityFile.txt"); //2. Connect to this server HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection(); InputStream inputStream = urlConnection.getInputStream(); FileOutputStream fos = new FileOutputStream("Security.txt"); byte[] buffer = new byte[1024]; int len; while ((len=inputStream.read(buffer))!=-1){ fos.write(buffer,0,len);//Write this data } fos.close(); inputStream.close(); urlConnection.disconnect();//Disconnect } }