Computer network
Computer network refers to a computer system that connects a number of independent computers and their external devices with different geographical locations through communication lines. Under the management and coordination of network operating system, network management software and network communication protocol, resources sharing and information transfer can be realized.
The purpose of network programming
- Radio station
- Spread and exchange information
- Data interchange
- communication
- .
Elements of network communication
How to realize network communication?
-
Address of the communication party
- IP – Locates a particular computer
- Port number – Locate to an application
- 47.99.72.134:1025
-
Communication protocol
- This section focuses on TCP and UDP at the transport layer
IP
IP address: InetAddress
- Uniquely locate a computer on a network
- 127.0.0.1: Local (localhost)
- IP Address Classification
- ipv4 / ipv6
- Ipv4:47.99.72.134, 4 bytes, total 4.2 billion; End of 2019
- Ipv6: CDCD: 910 a: 2222-5498:8475-1111:3900-2020128, each with 16 * *, * * is separated, every four expressed in a hexadecimal number, 2 ^ 128 (about 3.4 * 10 ^ 38)
- Public network/Private Network (LAN)
- The ABCD class address
- 192.168. XXX. XXX private network
- Domain name: IP address cannot be remembered
- ipv4 / ipv6
java.net.InetAddress
package com.volcano.net;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class TestInetAddress {
public static void main(String[] args) {
try {
InetAddress address = InetAddress.getByName("www.baidu.com");
System.out.println(address);/ / www.baidu.com/180.101.49.11
InetAddress address2 = InetAddress.getByName("127.0.0.1");
System.out.println(address2);/ / / 127.0.0.1
InetAddress address3 = InetAddress.getLocalHost();
System.out.println(address3);/ / DESKTOP - 9 poar2h / 10.238.60.12
} catch(UnknownHostException e) { e.printStackTrace(); }}}Copy the code
port
A port represents the process of a program on a computer.
-
Different processes have different port numbers
-
Regulations, 0 ~ 65535
-
TCP and UDP have 6W + each
-
Port classification
-
Public ports 0 to 1023 are mostly used by built-in applications
- 80 HTTP:
- HTTPS: 443
- FTP: 21
- Telnet: 23
-
Program registration port: 1024~49151 for assigning users or programs
- The Oracle: 1521
- Mysql: 3306
- Tomcat: 8080
-
Dynamic allocation or private: 49152 to 65535
Netstat ano# view all ports netstat ano | findstr searches "80" # view all specified port tasklist: findstr searches "80" # check the progress of the specified portCopy the code
-
java.net.InetSocketAddress
package com.volcano.net;
import java.net.InetSocketAddress;
public class TestInetSocketAddress {
public static void main(String[] args) {
InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1".8080);
System.out.println(inetSocketAddress);
InetSocketAddress inetSocketAddress2 = new InetSocketAddress("localhost".8080); System.out.println(inetSocketAddress2); System.out.println(inetSocketAddress.getAddress()); System.out.println(inetSocketAddress.getHostName()); System.out.println(inetSocketAddress.getPort()); }}Copy the code
Communication protocol
Network communication protocol: rate, bit rate, code structure, transmission control…
TCP/IP protocol cluster: Actually a group of protocols
Important:
- TCP: user transport protocol
- UDP: user datagram protocol
Famous agreement
- TCP
- IP
Comparison between TCP and UDP
TCP: Make a call
-
Connection, stabilization
-
Three handshakes, four waves
At least three times to ensure A stable connection A: What do you see? B: What do you think? A: Give it A go! Disconnect at least 4 times A: I'm leaving B: Are you really leaving? B: Are you really, really leaving? A: I really have to goCopy the code
-
Client, server
UDP: Sends SMS messages
- Not connected or stable
- Client, server: No clear boundaries
- Ready or not, I can send it to you
- DDOS: Flood attacks, sending spam messages, occupying target ports, and jamming the network
TCP
Implement chatting
package com.volcano.net;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
// Run this class first
public class TcpServerDemo1 {
public static void main(String[] args) {
// All need to be closed, so all need to be extracted first
ServerSocket serverSocket=null;
Socket socket=null;
InputStream socketInputStream=null;
ByteArrayOutputStream byteArrayOutputStream=null;
try {
//1. You must have an address first
serverSocket = new ServerSocket(9999);
// Loop to receive messages
while(true) {//2. Wait for the client to connect
socket = serverSocket.accept();
//3. Read client messages
socketInputStream = socket.getInputStream();
// Pipe flow is appropriate
byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len;
while((len=socketInputStream.read(buffer))! = -1){
byteArrayOutputStream.write(buffer,0,len); } System.out.println(byteArrayOutputStream.toString()); }}catch (IOException e) {
e.printStackTrace();
}finally {
// It is necessary to close all of them by using if to judge and then close them
if(byteArrayOutputStream! =null) {try {
byteArrayOutputStream.close();
} catch(IOException e) { e.printStackTrace(); }}if(socketInputStream! =null) {try {
socketInputStream.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();
}
}
}
}
}
Copy the code
package com.volcano.net;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class TcpClientDemo1 {
public static void main(String[] args) {
Socket socket=null;
OutputStream outputStream=null;
try {
//1. Obtain the server address
InetAddress address = InetAddress.getByName("127.0.0.1");
/ / the port number
int port = 9999;
2. Create a Socket connection
socket = new Socket(address, 9999);
//3. Send message I/O flow
outputStream = socket.getOutputStream();
outputStream.write("aaaa".getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally {
if(outputStream! =null) {try {
outputStream.close();
} catch(IOException e) { e.printStackTrace(); }}if(socket! =null) {try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Copy the code
Transfer files
package com.volcano.net;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TcpServerDemo02 {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9999);
Socket socket = serverSocket.accept();
InputStream socketInputStream = socket.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(new File("222.jpg"));
byte[] buffer = new byte[1024];
int len;
while((len=socketInputStream.read(buffer))! = -1){
fileOutputStream.write(buffer,0, len);
}
// After receiving the message, tell the client
OutputStream socketOutputStream = socket.getOutputStream();
socketOutputStream.write("I'm ready, you disconnect.".getBytes()); fileOutputStream.close(); socketInputStream.close(); serverSocket.close(); }}Copy the code
package com.volcano.net;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TcpClientDemo02 {
public static void main(String[] args) throws Exception {
Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
OutputStream outputStream = socket.getOutputStream();
// Create a file input stream
FileInputStream fileInputStream = new FileInputStream(new File("Tutor wallpaper.jpg"));
byte[] buffer = new byte[1024];
int len;
// The file is written to the socket output stream
while((len=fileInputStream.read(buffer))! = -1){
outputStream.write(buffer,0,len);
}
// When the transmission is complete, tell the server
socket.shutdownOutput();
// Result of receiving server message
InputStream socketInputStream = socket.getInputStream();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int len2;
byte[] buffer2 = new byte[1024];
while((len2=socketInputStream.read(buffer2))! = -1){
byteArrayOutputStream.write(buffer2,0,len2); } System.out.println(byteArrayOutputStream.toString()); fileInputStream.close(); outputStream.close(); socket.close(); }}Copy the code
UDP
Message is sent
package com.volcano.net;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UdpClientDemo {
public static void main(String[] args) throws Exception {
//1. Create a Socket
DatagramSocket socket = new DatagramSocket();
/ / 2. Set up a package
String msg = "Hello, server.";
// Send to destination
InetAddress localhost = InetAddress.getByName("localhost");
int port=9999;
DatagramPacket packet = new DatagramPacket(msg.getBytes(), 0, msg.getBytes().length, localhost, port);
/ / 3. Sendsocket.send(packet); socket.close(); }}Copy the code
package com.volcano.net;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpServerDemo {
public static void main(String[] args) throws Exception {
// Open the port
DatagramSocket socket=new DatagramSocket(9999);
// Receive the packet, still need to wait for the client to connect
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, 0, buffer.length);
socket.receive(packet);// block reception
System.out.println(packet.getAddress().getHostAddress());
System.out.println(new String(packet.getData(),0,packet.getLength())); socket.close(); }}Copy the code
Chat implementation
Multi-threaded chat.
Create send and receive threads
package com.volcano.net.chat;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class TalkSend implements Runnable {
DatagramSocket socket=null;
BufferedReader reader=null;
int thisPort;
String toHost;
int toPort;
public TalkSend(int fromPort, String toHost, int toPort) {
this.thisPort = fromPort;
this.toHost = toHost;
this.toPort = toPort;
}
@Override
public void run(a) {
try {
socket = new DatagramSocket(thisPort);
// Prepare data: console read
reader = new BufferedReader(new InputStreamReader(System.in));
// Send in a loop
while (true){
String data = reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas,0,datas.length, InetAddress.getByName(toHost),toPort);
socket.send(packet);
if(data.equals("bye")) {break; }}}catch(IOException e) { e.printStackTrace(); } socket.close(); }}Copy the code
package com.volcano.net.chat;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class TalkReceive implements Runnable {
DatagramSocket socket=null;
int thisPort;
String fromWho;
public TalkReceive(int thisPort, String fromWho) {
this.thisPort = thisPort;
this.fromWho = fromWho;
}
@Override
public void run(a) {
try {
socket = new DatagramSocket(thisPort);
// loop to receive
while (true) {byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer,0,buffer.length);
socket.receive(packet);
byte[] data=packet.getData();
String strData=new String(data,0,data.length);
System.out.println(fromWho+":"+strData);
if(strData.trim().equals("bye")) {break;
}
}
socket.close();
} catch(IOException e) { e.printStackTrace(); }}}Copy the code
Run the thread on the student side and the teacher side, note the port correspondence
package com.volcano.net.chat;
public class Student {
public static void main(String[] args) {
new Thread(new TalkSend(6666."localhost".9999)).start();
new Thread(new TalkReceive(8888."Teacher")).start(); }}Copy the code
package com.volcano.net.chat;
public class Teacher {
public static void main(String[] args) {
new Thread(new TalkSend(7777."localhost".8888)).start();
new Thread(new TalkReceive(9999."Student")).start(); }}Copy the code
URL
Uniform resource locator
package com.volcano.net;
import java.net.MalformedURLException;
import java.net.URL;
public class TestURL {
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());/ / the full path
System.out.println(url.getQuery());/ / parameters}}Copy the code
Download Network resources
package com.volcano.net;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class UrlDown {
public static void main(String[] args) throws IOException {
//1. Download address
URL url = new URL("xxxxxxx");// Enter a valid resource URL
2. Connect to the resource HTTP
HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream outputStream=new FileOutputStream("a.txt");
byte[] buffer=new byte[1024];
int len;
while((len=inputStream.read(buffer))! = -1){
outputStream.write(buffer,0,len); } outputStream.close(); inputStream.close(); urlConnection.disconnect(); }}Copy the code