Java Socket-based UDP communication

Preface

Three elements of network programming: IP, port number, protocol 

IP: The unique identification of each device in the network, each network terminal has an independent address in the network, we use this address to transmit data on the network.

Port number: The unique identification of each program on the device. Each network program needs to be bound to a port number. When transmitting data, in addition to determining which machine to send to, it is also necessary to specify which program to send to. The port number ranges from 0-65535. To write a network application, you need to bind a port number. Try to use the port number above 1024. The ones below 1024 are basically occupied by system programs.

Protocol: A collection of rules, standards, or agreements established for data exchange in a computer network;

      UDP: For connectionless, data is insecure and fast. Does not distinguish between client and server.

      TCP: connection-oriented (three-way handshake), data security, slightly lower speed. Divided into client and server.

UDP transmission

The udp transmission does not distinguish between the server and the client, and the sender and receiver are determined by the send and receive methods of DatagramSocket;

Sending end (Send)

The main steps are as follows:

1. Create DatagramSocket, random port number
2. Create DatagramPacket, specify data, length, address, port
3. Use DatagramSocket to send DatagramPacket
4, close DatagramSocket

public class Send {
	public static void main(String[] args) throws IOException {
		send1();
	}

	private static void send1() throws SocketException, UnknownHostException, IOException {
		Scanner s = new Scanner(System.in);
		DatagramSocket socket = new DatagramSocket(); //随机端口号
		while(true) {
			String data= s.nextLine();
			byte[] b = data.getBytes();
			if("拜拜".equals(data)) {
				break;
			}
			DatagramPacket packet = new DatagramPacket(b, b.length,InetAddress.getByName("127.0.0.1"), 8888);
			socket.send(packet);
		}
		socket.close();
	}
}

Receiving end

1. To create a DatagramSocket, you must specify a port
2. Create a DatagramPacket, specify an array, length
3. Use DatagramSocket to receive DatagramPacket
4, get data from DatagramPacket
5, close DatagramSocket

public class Receive {
	
	public static void main(String[] args) throws IOException {
		receve1();
	}
	
	private static void receve1() throws SocketException, IOException {
		DatagramSocket socket = new DatagramSocket(8888);
		DatagramPacket packet = new DatagramPacket(new byte[64],64);
		while(true) {
			socket.receive(packet);
			byte[] re=packet.getData();
			System.out.println(new String(re,0,packet.getLength()));
		}
	}	
}

 

Guess you like

Origin blog.csdn.net/ezconn/article/details/108479326