UDP communication between the two sides is also divided into the client and server, but in the personal understanding of this aspect of UDP is not strictly differentiated, send the request for the client, responding to the request for the service side.
To use UDP in Python, you first import the socket
s = socket.socket (socket.af_inet, socket. SOCK_DGRAM)
In the example above, a IPv4, UDP socket was created,
Among them, socket.af_inet is IPv4 type, Socket.af_inet6 is IPv6 type;
Socket. SOCK_DGRAM is the UDP protocol, socket. Sock_stream for TCP protocol
Then you want to bind the address (127.0.0.1 is the local IP address)
Host = ' 127.0.0.1 ' port = 7788s.bind ((host, Port))
This is bound to the IP address and port number, if the port port number is default, the system assigns a port to this socket by default, it is recommended to use the default port binding address, because this will not avoid port conflicts.
Data=b ' hello! ' S.sendto (data, (' 127.0.0.1,9999 '))
Send data to 127.0.0.1 port 9999 hello!
Accept Data
While True: data, addr = S.recvfrom (1024)
The Recvfrom method parameter value of the socket used to receive data is the number of bytes of data received each time, in the above example, each time you receive 1024 of your data, because not every time you can accept all the data at once, all in the loop.
In general, like the previous example of the loop to accept data, will contract a protocol, accept what kind of data to end the loop, the above example did not write.
The received data has two values, data for the other wants to send, addr for each other's address
Attention:
The data sent and received is a byte stream, note encoding and decoding.
Broadcasting
Because of the nature of UDP, is to the address of a contract, the other, no matter, do not need to connect, so there is the use of broadcasting (specifically, IP-related knowledge, not to do the detailed here)
Broadcast packets are routed to all computers involved in the host ID segment. For example, for a 10.1.1.0 (255.255.255.0) network segment, its broadcast address is 10.1.1.255 (255 is 2 binary 11111111)
#dest = (' 192.168.1.255 ', 7788) #要是广播地址不在dest上, you cannot use #<broadcast> to automatically get the current broadcast address dest = (' <broadcast> ', 7788) s = Socket.socket (Socket.af_inet,socket. SOCK_DGRAM) #要发送广播, this sentence must have s.setsockopt (socket. Sol_socket,socket. so_broadcast,1)
Send data as usual after
Cond
Python Learning log--udp socket use