Java Network Programming Foundation - Transport Layer Protocol TCP&UDP

1. Network programming foundation

1. Network and network card

Network is the first driving force of current information technology
. There are several network cards on each computer equipment.
Each network card has a unique hardware address and MAC address in the world.

2. IP address: Each network card/machine has one or more IP addresses

IPV4: 192.168.0.100, each segment is 0 to 255
IPV6: 128bit long, divided into 8 segments, each segment is 4 hexadecimal numbers
The machine reserved IP: 127.0.0.1
Windows through ipconfig query, Linux/Mac through ifconfig

3.Port, 0-65535

0-1023, OS and occupied, 80 is Web, 23 is teleent
1024-65535, general programs can be used (beware of conflicts)
The communication between the two machines is performed on IP+Port
Windows/Linux/Mac is queried by netstat -an

4. Public (World Wide Web/Internet) and Intranet (LAN)

The network is layered,
the outermost layer is the public network/Internet
, and each layer below is the intranet
IP address. You can use
tracert on each layer of the network to see the access relay of the current machine and the target machine.

5. Transport layer communication protocol

TCP (Transmission Control Protocol)
transmission control protocol, connection-oriented protocol
Reliable and error-free data transmission between two machines
Bidirectional byte stream transmission
UDP (User Datagram Protocol)
user datagram protocol, connectionless protocol
does not guarantee reliable data The transmission
speed is fast, and it can also be used in poor network environment

6. Computer Communication

Data is sent from one IP port (sender) and transported to another IP port (receiver)

2. UDP: Connectionless and stateless communication protocol

1. Features

The sender sends a message. If the receiver happens to be at the destination, it can be received. If not, the message will be lost. The
sender cannot know whether the message is sent successfully
. The advantages of UDP are simplicity, savings, and economy.

2. Ideas

The data pipeline ds that establishes communication
through DatagramSocket ds that establishes data container dp
through DatagramPacket passes the message bytecode and message bytecode length into DatagramPacket
If it is the sender, then the incoming address label: destination IP+Port
through InetAddress.getByName ("IP") Incoming address
send method implements sending and receive method implements receiving
. The receiver must execute before the initiator

3.demo:UdpRecv

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UdpRecv {
    
    
    public static void main(String[] args) throws Exception
    {
    
    
        //定义管道为本机3000端口
        DatagramSocket ds=new DatagramSocket(3000);
        //定义字节数组存放信息
        byte [] buf=new byte[1024];
        //定义集装箱,用来封装信息
        DatagramPacket dp = new DatagramPacket(buf,1024);

        System.out.println("UdpRecv: 我在等待信息");
        //等待信息,如果有信息过来,则会封装在dp中
        //如果没有信息过来,则会造成阻塞
        ds.receive(dp);
        System.out.println("UdpRecv: 我接收到信息");
        
        //dp.getAddress().getHostAddress()方法获取IP
        //dp.getPort()方法获取Port
        String strRecv=new String(dp.getData()) +
                " from " + dp.getAddress().getHostAddress()+":"+dp.getPort();
        //打印信息和信息的来源地址
        System.out.println(strRecv);

        //线程暂停1s
        Thread.sleep(1000);
        
        //设置将要发送的信息
        String str="hello yh";
        //定义集装箱,装入dp内容和长度并且贴了目的地
        //目的地为127.0.0.1:3000
        //str.getBytes()方法把str类型转化为byte类型
        //str.length()
        //地址标签:目的地IP+Port
        DatagramPacket dp2=new DatagramPacket(str.getBytes(),str.length(),
                InetAddress.getByName("127.0.0.1"),dp.getPort());
        
        System.out.println("UdpRecv: 我要发送信息");
        //发送信息
        ds.send(dp2);
        System.out.println("UdpRecv: 我发送信息结束");
        
        //关闭管道
        ds.close();
    }
}

4.demo:UdpSend

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;

public class UdpSend {
    
    
    public static void main(String [] args) throws Exception
    {
    
    
        //DatagramSocket:通讯的数据管道
        //定义管道
        DatagramSocket ds = new DatagramSocket();
        //定义将要发送的信息
        String str = "hello henrik";
        //定义集装箱,装入dp内容和长度并且贴了目的地
        //目的地为127.0.0.1:3000
        //str.getBytes()方法把str类型转化为byte类型
        //str.length()
        //地址标签:目的地IP+Port
        DatagramPacket dp = new DatagramPacket(str.getBytes(),str.length(),
                InetAddress.getByName("127.0.0.1"),3000);

        System.out.println("UdpSend: 我要发送信息");
        //发送信息
        ds.send(dp);
        System.out.println("UdpSend: 我发送信息结束");

        //进程暂停1s
        Thread.sleep(1000);

        //定义字节数组存放信息
        byte [] buf=new byte[1024];
        //定义集装箱用来封装信息
        DatagramPacket dp2 = new DatagramPacket(buf,1024);

        System.out.println("UdpSend: 我在等待信息");
        ds.receive(dp2);
        System.out.println("UdpSend: 我接收到信息");

        //dp.getAddress().getHostAddress()方法获取IP
        //dp.getPort()方法获取Port
        String str2 = new String(dp2.getData()) +
                " from " + dp2.getAddress().getHostAddress()+":"+dp2.getPort();
        //打印信息和信息的来源地址
        System.out.println(str2);

        //关闭管道
        ds.close();
    }
}

5. Effects
insert image description here
insert image description here

3. TCP: There is a connection to ensure a reliable communication protocol

1. Ideas

The server creates a ServerSocket and waits for a connection
The client creates a Socket,
the ServerSocket connected to the server receives the connection, creates a Socket and establishes a dedicated connection with the client's Socket, and the subsequent dialogue between the server and the client (this pair of Sockets) will be in a Running on a separate thread (server),
the ServerSocket of the server continues to wait for a connection

2. Features

When the server waits for a response, it is in a blocking state . The
server can respond to multiple clients at the same time
. Each time the server accepts a client, it starts an independent thread corresponding to it
. Both the client and the server can choose to close the channel of the pair of Sockets
ServerSocket As the port of the server, you need to bind the port. If there are multiple network cards, you need to bind an IP address
Socket as the transport channel. The client writes data to the socket input stream, sends it to the server, and takes the server from the socket output stream. data, server side and vice versa

3.demo:TcpServer


import java.net.*;
import java.io.*;
import java.nio.charset.StandardCharsets;

public class TcpServer
{
    
    
	public static void main(String [] args) 
	{
    
    
		try{
    
    
			//驻守在8001端口
			ServerSocket ss = new ServerSocket(8001);
			//等待客户端连接
			Socket s = ss.accept();
			//阻塞提示
			System.out.println("welcome to the java world");
			//有人连接上打开输入流
			InputStream ips = s.getInputStream();
			//打开输出流
			OutputStream ops = s.getOutputStream();
			//同一个通道,服务端的输出流输入流就是客户端的输出流输入流

			//输出一句话给客户端
			ops.write("hello client".getBytes());


			//从客户端读取一句话
			BufferedReader br = new BufferedReader(new InputStreamReader(ips));
			System.out.println("client said:"+br.readLine());



			//关闭各对象
			ips.close();
			ops.close();
			s.close();
			ss.close();
		} catch (IOException exception) {
    
    
			exception.printStackTrace();
		}
	}
}

4.demo:TcpClient

import java.net.*;
import java.io.*;

public class TcpClient {
    
    
	public static void main(String[] args) {
    
    
		try {
    
    
			//用地址标签创建通道,这里需要服务端先开启
			Socket s = new Socket(InetAddress.getByName("127.0.0.1"), 8001);

			//同一个通道,服务端的输出流就是客户端的输入流;服务端的输入流就是客户端的输出流
			//开启通道的输入流
			InputStream ips = s.getInputStream();
			BufferedReader brNet = new BufferedReader(new InputStreamReader(ips));

			//开启通道的输出流
			OutputStream ops = s.getOutputStream();
			//包装输出流
			DataOutputStream dos = new DataOutputStream(ops);

			//键盘录入信息
			//System.in是一个位流,InputStreamReader转换为字符流,然后再使用BufferedReader为其增加缓冲功能
			BufferedReader brKey = new BufferedReader(new InputStreamReader(System.in));
			while (true)
			{
    
    
				String strWord = brKey.readLine();
				//判断是否为换行,换行则表示结束
				if (strWord.equalsIgnoreCase("quit"))
				{
    
    
					break;
				}
				else
				{
    
    
					System.out.println("I want to send: " + strWord);
					//System.getProperty("line.separator")获取操作系统对应的换行符
					dos.writeBytes(strWord + System.getProperty("line.separator"));
					System.out.println("Server said: " + brNet.readLine());
				}

			}

			//关闭对象
			dos.close();
			brNet.close();
			brKey.close();
			s.close();
		} catch (Exception e) {
    
    
			e.printStackTrace();
		}
	}
}

5. Effects
insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/qq_50216270/article/details/117298960