当前位置:网站首页>UDP connection map collection

UDP connection map collection

2022-06-13 03:37:00 Mouth strong programmer

1. Overview of network communication elements
    IP Address and port number / Network communication protocol

2. Network communication protocol ( With TCP/IP The model, for example )

     Common network communication protocols :TCP/IP agreement 、IPX/SPX agreement 、NetBEUI Agreements, etc .

    **** international standard ****
       TCP/IP, namely Transmission Control Protocol/Internet Protocol Abbreviation
     Transmission control protocol / Internet Interconnection Protocol , yes Internet The most basic agreement 、Internet The foundation of Internet .


3.IP Address and port number ( Combination is network socket )
    URL url = new URL(" File address ");
    3.1 IP Address :InetAddress( stay Java Use in InetAddress Class representative IP)

    3.2 Port number
         The port number identifies the process running on the computer ( Program )
         Different processes have different port numbers
         To be defined as a 16 An integer 0~65535.

        
4.TCP|IP The transport layer in the model 2 It's an important agreement :TCP The protocol and UDP agreement


5.TCP protocol
    (1) Use TCP Before the agreement , Must be established first TCP Connect , Form a transmission data channel

    (2) Before transmission , use “ Three handshakes ” The way , Point to point communication , Is reliable . Four waves

    (3) TCP Protocol for communication between two application processes : client 、 Server side .

    (4) A large amount of data can be transmitted in the connection

    (5) Transmission complete , To release an established connection , Low efficiency
    
    

6.UDP protocol ( There is no connection )
    (1) Put the data 、 Source 、 The purpose is encapsulated in packets , No connection needed

    (2) The size of each datagram is limited to 64K Inside ( Send as a container )

    (3) Send whether the other party is ready or not , The receiving party does not acknowledge the receipt , Therefore, it is unreliable

    (4) It can be broadcast

    (5) There is no need to release resources at the end of sending data , Low overhead , Fast
    

The sender   Receiving party
    DatagramSocket---- Compare to the sender     Compare to the receiver
    DatagramPacket----- Data packaging objects
    
    
    
    
    
    
    
    
    

7.TCP Network programming
     be based on Socket The socket implements the dialogue between the server and the client


8.UDP Network programming
    8.1 UDP Network communication
        UDP There is no such thing as server and client .
         Sender and receiver
        a. class DatagramSocket and DatagramPacket Based on UDP Protocol network program .


        b.UDP Datagram through datagram socket DatagramSocket Send and receive , The system does not guarantee UDP Datagrams must be delivered safely to their destinations , I'm not sure when I'll arrive .


        c.DatagramPacket Object encapsulates UDP The datagram , The datagram contains the sender's IP Address and port number as well as the receiver's IP Address and port number .


        d.UDP Each datagram in the protocol gives the complete address information , Therefore, there is no need to establish a connection between the sender and the receiver . It's like sending an express package .


    8.2 UDP Network communication process

        1、DatagramSocket And DatagramPacket


        2、 Set up the sender , The receiver
        

        3、 Building packets

        4、 call Socket Sending of 、 Receiving method


        5、 close Socket

Be careful : The sender and receiver are two independent running programs

    8.3 With unicast , multicast , The function of broadcasting
        UDP It supports more than one-to-one transmission , Also support one to many , Many to many , Many to one way , in other words UDP Provides unicast , multicast , The function of broadcasting .


    8.4 unicast
         It refers to the transmission of packets in the computer network , A transmission in which the destination address is a single destination .
        【 You shout to xiaoyueyue “ Little moon ”, Then only xiaoyueyue turns around to promise you .】

    8.5 radio broadcast
         When packets are transmitted in a computer network , The destination address is a transmission mode of all devices in the network . actually , What I'm talking about here “ All devices ” It's also limited to one area , be called “ Broadcast area ”.
        255.255.255.255        
        【 You shout at the company “ be on holiday ”, All colleagues will respond , It's amazing to shout .】        

    8.6 Multicast
         It's also called multicast , To broadcast or group . The simultaneous delivery of information to a set of destination addresses . It uses strategies that are most efficient , Because messages only need to be delivered once per network link , And only when the link forks , The message will be copied .

Multicast group through D class IP Address and standard UDP Port number specification .D class IP The address in 224.0.0.0 and 239.255.255.255 Within the scope of ( Including both ). Address 224.0.0.0 Reserved , Should not be used .
        【 You shout out in the street “ beauty ”, There will be a group of women looking back at you .】
         Sent IP Address :238.222.111.0
         The receiving party :
        MulticastSocket ms=new MulticastSocket(4399);
        /* Join that group ? */
        ms.joinGroup(InetAddress.getByName("238.222.111.0"));
        byte[] bs=new byte[100];
        DatagramPacket dp=new DatagramPacket(bs, bs.length);
        ms.receive(dp);
        System.out.println(new String(bs).trim());
        /* Leave the group */
        ms.leaveGroup(InetAddress.getByName("238.222.111.0"));
        ms.close();

===================================================================================================
udp: The data packet ( package ) agreement
DatagramPacket==== Transport layer
                        =====UDP
DatagramSocket==== Transport layer
There are three kinds of :
unicast : It refers to sending packets to only one fixed machine
radio broadcast : Is to 255.255.255.255 send out , All machines listening to a port can receive
Multicast : Is to send to a user group , All users in this group can receive


DatagramPacket Yes 2 A role
1. Packets sent ===> To give the content to be sent and the address and port to be sent
DatagramPacket dp = 
new DatagramPacket(byte[],0,length,InetAddress,port);
2. Received packets ===> Just specify the size of the received packet
DatagramPacket dp = 
new DatagramPacket(byte[],0,length);

DatagramSocket Yes 2 A role
1. Sent by ===> It only needs new Just come out
DatagramSocket ds = new DatagramSocket();
2. The recipient ===> You need to specify the receiving address and port
DatagramSocket ds = new DatagramSocket(port,InetAddress);

For three udp agreement
1. The sender is exactly the same , Unicast is to specify a ip
Broadcasting is designated 255.255.255.255 This ip
Multicast is to specify D class ip(224-239)
2. The receiver unicast directly specifies a ip And port
Broadcast cannot specify ip, Just port
Multicast should use MulticastSocket,
And then use joinGroup Join the group

 

 DatagramSocket Create the use of the receiving end

  The sender

package com.zking.test02;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

// The sender 
public class FileSender {
	public static void main(String[] args) throws Exception{
		System.out.println("--------- The sender -----------");
		DatagramSocket ds = new DatagramSocket();
		System.out.println(" The sender is turned on ");
		// Send a file 
		File file = new File("D:\\1.jpg");
		// byte 
		FileInputStream fis = new FileInputStream(file);
		BufferedInputStream bis = new BufferedInputStream(fis);
		DatagramPacket dp = null;
		// Read one byte array at a time (10 A unit of )---- Immediately via datagram   Package and send 
		byte[] buf = new byte[1024];
		int len = 0;
		int count = 0;
		while(-1!=(len = bis.read(buf))) {
			// Create datagram objects    Pack the byte array read each time 
			dp = new DatagramPacket(buf, buf.length, InetAddress.getByName("127.0.0.1"), 8989);
			// send out 
			ds.send(dp);
			count+=10;
//			Thread.sleep(50);
			System.out.println(count);
		}
		
		// Send a specific representation 
		
		dp = new DatagramPacket("xb".getBytes(), "xb".getBytes().length, InetAddress.getByName("127.0.0.1"), 8989);
		ds.send(dp);
		
		
		ds.close();
		System.out.println(" sent !!!");
		//sb
		
		
		// unicast      Multicast    radio broadcast 
	}
}

  The receiving end

package com.zking.test02;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

// The receiver 
public class FileReceive {
	public static void main(String[] args) throws Exception{
		System.out.println("--------- The receiver -----------");
		DatagramSocket ds = new DatagramSocket(8989);
		System.out.println(" The receiving end has been turned on ");
		DatagramPacket dp = null;
		byte[] buf = new byte[1024];
		// Create output stream 
		File file = new File("D:\\Zking\\ beauty .jpg");
		FileOutputStream fos = new FileOutputStream(file);
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		while(true) {
			dp = new DatagramPacket(buf, buf.length);// Receive packets 
			// Call the method that receives the activation 
			ds.receive(dp);
			byte[] data = dp.getData();
			int n = dp.getLength();
			if("xb".equals(new String(data,0,n))) {
				System.out.println(" End of reception ");
				break;
			}
			// Write to local file 
			bos.write(buf);
			bos.flush();
		}
		
		// close 
		bos.close();
		fos.close();
		ds.close();
		
		
	}
}

Map Use of collections !

package com.zking.test03;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Demo_03 {
	public static void main(String[] args) {
//		Collection aggregate 
//		 Single column set -- Only one data can be stored at a time 
//		List|Set
//		List: Orderly     Element repeatable 
//		ArrayList|LinkedList|Vector
//		Set: disorder      only 
//		HashSet
		
//		List<String> list = new ArrayList<String>();
//		
//		list.add("agds");
//		size()
//		clear
//		get
//		contains
//		isEmpty
//		remove
		
		
//		List<String> list = new ArrayList<String>();
//		list.add("agds1");
//		list.add("agds2");
//		list.add("agds4");
//		list.add("agds3");
//		list.add("agds5");
//		list.add("agds6");
//		for (int i = 0; i < list.size(); i++) {
//			System.out.println(list.get(i));
//		}
//		for (String string : list) {
//			System.out.println(string);
//		}
//		// The way of iterator 
//		Iterator<String> iterator = list.iterator();
//		while(iterator.hasNext()) {
//			System.out.println(iterator.next());
//		}
		
		//Map aggregate : Double column set    newly added  ---- You can add 2 Data 
		// Stored data is stored in the form of key value pairs .
		// Key is unique      Values can be repeated 
		// Common implementation classes   HashMap
		
		// Create a Map aggregate 
//		Map map = new HashMap();
//		
//		// newly added 
//		map.put(" Yang2 guo4 ", " Steamed Dumplings ");
//		map.put(" Peng Yong ", " Cui Hua ");
//		map.put(" Lao Wang ", " Xiong Mei ");
//		map.put(" Tang Ye ", " Widow Wang ");
//		map.put(" yoga ", " Widow Wang ");
//		// size 
//		System.out.println(map.size());//5
		//clear Empty 
//		map.clear();
//		System.out.println(map.size());
		// Determines if the set is empty 
//		System.out.println(map.isEmpty());
		
		
		// Get all values 
//		Collection values = map.values();
//		for (Object object : values) {
//			System.out.println(object);
//		}
		
		// Get all keys 
//		Set keySet = map.keySet();
//		for (Object object : keySet) {
//			System.out.println(object);
//		}
		
//		 Get value from key 
//		Object object = map.get(" yoga ");
//		System.out.println(object);
//		
//		
//		// demand : Yes map Traversal    Output all keys and values at the same time   One-to-one correspondence 
//		Set keySet = map.keySet();// Get all the keys 
//		for (Object object2 : keySet) {
//			// Get the corresponding value according to the key 
//			Object object3 = map.get(object2);
//			System.out.println(object2+"---"+object3);
//		}
		// Never use 
		
		//Entry Entity + iterator 
		
		//1. take Map Each pair of key value pairs in the set is encapsulated into Entry Entity object , Take the key and value as its properties 
		//2. take Entry Convert to iterator and iterate again 
		
//		Map<String,String> map = new HashMap<String,String>();
//		// newly added 
//		map.put(" Yang2 guo4 ", " Steamed Dumplings ");
//		map.put(" Peng Yong ", " Cui Hua ");
//		map.put(" Lao Wang ", " Xiong Mei ");
//		map.put(" Tang Ye ", " Widow Wang ");
//		map.put(" yoga ", " Widow Wang ");
//		
//		//map Collection call entrySet Methods will map The key value pairs in the collection are encapsulated into Entry The entity object returns Set aggregate 
//		Set<Entry<String, String>> entrySet = map.entrySet();
//		//set Traversal by iterator 
//		Iterator<Entry<String, String>> iterator = entrySet.iterator();
//		while(iterator.hasNext()) {
//			Entry<String, String> next = iterator.next();
//			System.out.println(next.getKey()+"--"+next.getValue());
//		}
		
		//Map Storage types in the collection    
		
		// No generic type specified    Default Object
		Student stu = new Student(123, "asd");
		Student stu3 = new Student("123", "asd");
		//int
		Student<Integer> stu2 = new Student<Integer>(1, "123");
		//String
		Student<String> stu4 = new Student<String>("123", "123");
		
		// Terror 
//		Map<List<Student<String>>,List<List<String>>> map = new
//				HashMap<List<Student<String>>, List<List<String>>>();
		
		
		// Opened a prison     Yes 10 Room ( prison 1234)    Each room has 20 A prisoner 
		//Map Simulate one click generation    Print out prisoners in all rooms 
		Map<String,List<FanRen>> map = new HashMap<String,List<FanRen>>();
		// Loop simulation 10 Room 
		for (int i = 1; i <= 10; i++) {
			// Each room has 20 A prisoner 
			List<FanRen> list = new ArrayList<FanRen>();
			for (int j = 1; j <= 20; j++) {
				list.add(new FanRen(j+1, " Zhang San "+j));
			}
			// Generated 10 Interposition    And every room 20 Individuals join together Map aggregate 
			map.put(" prison "+i+" Number ", list);
		}
		
		// Traverse 
		Set<Entry<String, List<FanRen>>> entrySet = map.entrySet();
		// iterator 
		Iterator<Entry<String, List<FanRen>>> its = entrySet.iterator();
		while(its.hasNext()) {
			Entry<String, List<FanRen>> next = its.next();
			String key = next.getKey();// key 
			System.out.println(key);
			// Get value 
			List<FanRen> value = next.getValue();
			for (FanRen fanRen : value) {
				System.out.println("\t"+fanRen);
			}
		}
		
	}
}

原网站

版权声明
本文为[Mouth strong programmer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280529564043.html

随机推荐