1. Introduction of UDP
The Internet protocol set supports a connectionless transport protocol called user Datagram Protocol (UDP). UDP provides a means for applications to send encapsulated IP packets without having to create them.
The Transport layer of the Internet has two protocols that complement each other. Connectionless is UDP, which does little more than send packet capabilities to applications and allow them to construct their own protocols at the level they need. Connection-oriented is TCP, which does almost everything.
Chinese name: User data protocol
User Datagram Protocol
Features: No connection, unreliable, fast transmission
Basics: Added a bit of functionality to the IP packet service
Category: Transport layer protocol
Purpose: To send data packets
2.socket
A socket is called a socket, and Python has a socket library (you can download the PIP install socket yourself using the PIP command). The following is the simple process of socket:
1. Obtain the socket
2. Bind ports
3. Select Send or accept
4. Close the socket
2-1 Sending the socket
Socket sending is very simple, the following is the general simplest code:
# -*- coding: utf-8 -*- import socket def sendMsg(): Send_socket = socket.socket(socket.af_inet, socket.sock_dgram) # bind the socket port to the IP address # The following number is the port number bound to the program. If you do not bind a port number in advance, the computer may automatically issue a port number to the program when it is sent. Send_socket.bind (("", 7879)) # Send_socket. sendto(b"123", ("127.0.0.1", 7878)) # Close the socket send_socket.close() if __name__ == '__main__': sendMsg()Copy the code
2-2 Receiving the socket
Note that in RECV, the port must be pre-bound because this is a prerequisite for receiving messages, so which port to choose? Generally when doing experiments or writing programs, we can choose between [1024-65535] port range. Because the sending of the socket has been created and the port number is 7878, we only need to bind the port 7878.
Recv_socket. recvfrom(1024) indicates that the maximum number of bytes accepted at a time is 1024. If the value exceeds this value, only the first 1024 bytes are taken. And the value returned by this function is a tuple, the same as when the socket sent (b”123″, (“127.0.0.1”, 7878)), so you need to use the subscript index to get the accepted content. We need to pay attention to this, because we transmit by bytes, so we also get bytes, and we need to encode it. However, The Win system is different from the Linux system. By default, the WIN system uses GBK encoding, while Linux uses UTF-8 encoding. You need to select the corresponding decoding format according to the system type.
# -*- coding: utf-8 -*- import socket def recvMsg(): Recv_socket = socket.socket(socket.af_inet, socket.sock_dgram) Recv_data = recv_socket. Recvfrom (1024) # print(" received from {}, {} information ". The format (recv_data [1], recv_data [0]. The decode (" GBK "))) # close socket recv_socket. Close () if __name__ = = "__main__ ': the recvMsg ()Copy the code
3. Implement the sending and receiving function
We need to know some knowledge in advance: simplex: can only receive or send, half duplex: can receive or send, but can not run at the same time, full duplex: can receive or send at the same time. In addition, the socket can receive and send data at the same time, so the socket is full-duplex.
The following code is to achieve the socket send and receive function
# -*- coding: utf-8 -*- import socket def SendAndRecv(): "" "socket is can send and receive data at the same time the simplex: only accept or send half duplex: can be closed, but you can't run at the same time full-duplex: the same time can charge can send notice: Socket = socket. Socket (socket.AF_INET, socket.sock_dgram) Sendto (b"hahahah", ("127.0.0.1", Recv_data = udp_socket.recvfrom(1024) print(" received from {}, {} information ". The format (recv_data [1], recv_data [0]. The decode (" GBK "))) # close socket udp_socket. Close () if __name__ = = "__main__ ': SendAndRecv()Copy the code
The code above does look a little ugly. Let’s wrap it up a little bit
# -*- coding: utf-8 -*- import socket def send_msg(udp_socket): Sendto (b'124124', ("127.0.0.1", 7788)) def recv_msg(socket): "" "receiving data "is" "recv_data = udp_socket. Recvfrom (1024) print (" % s: % s" % (STR (recv_data [1]), Recv_data [0].decode(" GBK ")) # Decode (utF-8) def main(): Socket = socket. Socket (socket.AF_INET, socket.SOCK_DGRAM) 7789)) # loop to process things while True: Print (" -- -- -- -- -- - the DreamsPy chat device -- -- -- -- -- - ") print (" 1: send a message ") print (" 2: receive messages ") print (" 0: exit system ") the op = input (" please input function: ") if the op = = "1" : Recv_msg (udp_socket) elif op == "0": break else: send_msg(udp_socket) elif op == "0": Print (" you enter the command is wrong, please input again ") if __name__ = = "__main__ ': the main ()Copy the code
The above code realizes the acceptance and sending of the program. However, we need to write two programs to verify whether it can be executed. The following two are the detection codes sent and received.
# -*- coding: utf-8 -*- import socket def recvMsg(): Recv_socket = socket.socket(socket.af_inet, socket.sock_dgram) Recv_data = recv_socket. Recvfrom (1024) # print(" received from {}, {} information ". The format (recv_data [1], recv_data [0]. The decode (" GBK "))) # close socket recv_socket. Close () if __name__ = = "__main__ ': the recvMsg ()Copy the code
The above code is whether the main program receive can be implemented.
# -*- coding: utf-8 -*- import socket def sendMsg(): Send_socket = socket.socket(socket.af_inet, socket.sock_dgram) # set send_socket.sendto(b"123", ("127.0.0.1", # 7789) close the socket send_socket. Close () if __name__ = = "__main__ ': sendMsg ()Copy the code
The above code is whether the main program send can be implemented.
Of course, for the sake of preciseness, you can also add while True to the main function for infinite loop to verify, and users can manually enter the IP address, port number, send content. I’m not going to write it out here, but I’ll leave the rest to you.
This is python chat applets written using sockets. The idea is relatively simple, the code is relatively easy to use. TCP is also a focus (will be sent later), review and practice more yo.