To communicate with each other, there are two ways of udp and tcp. Like our qq, udp and tcp coexist, but now qq is gradually being transformed into a tcp server.
Below is the chat window implemented with udp.
import socket
def send_msg(upd_socket):"""send messages"""
# Get what to send
dest_ip =input("Please enter the other party's ip address:")
dest_port =int(input("Please enter the other party's port number:"))
send_data =input("Please enter the message to be sent")
upd_socket.sendto(send_data.encode("utf-8"),(dest_ip, dest_port))
def recv_msg(upd_socket):
# Receive data and display
recv_data = upd_socket.recvfrom(1024)print("%s:%s"%(recv_data[0].decode("utf-8"),str(recv_data[1])))
def main():
# Create socket
upd_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Binding information
upd_socket.bind("",7788)
# Loop to process things
while True:send_msg(upd_socket)recv_msg(upd_socket)if __name__ =="__main__":main()
I recommend a format for writing code, like this, we first build the basic framework
def main():
pass
# 1. Create socket
# 2. Bind local information
# 3. Know the destination address and port number
# 4. Receive data and display
# 5. Close socket
if __name__ =="__main__":main()
This is the basic step. We first conceived it, so we started to write the representative. The code is relatively fixed. What we need to question is whether we use utf-8 or gbk when sending and receiving data. Suppose We are a linux system and the target is a Windows system, so the data we send needs to be encoded with .encode ("gbk"), and when we receive the data, it is decoded with .decode ("gbk") so that it can be correctly accepted Chinese characters.
Then, to make our main program look clearer, we will send and receive messages and wrap them into two functions, which are ** def send_msg(upd_socket): ** and ** def recv_msg(upd_socket): **Note , Whenever we create a new function, we must think about whether this function requires parameters.
You may see that at the end, I did not write udp_socket.close() to close the socket, because we will find at the end that we don't need to call close.
In pyhton, when we use a loop, don't write 1, but write True
For more wonderful articles about python chat function, please click the topic: python chat function summary
The above is the whole content of this article, I hope it will be helpful to everyone's study.
Recommended Posts