SoFunction
Updated on 2024-11-21

python implementation of udp chat window

To realize communication with each other, there are udp and tcp two ways, like our qq, is udp and tcp two ways to coexist, but now qq is gradually converted to tcp server.

Here is the chat window using udp.

import socket
def send_msg(upd_socket):
 """Send message"""
 # Get the content to be sent
 dest_ip = input("Please enter the other party's ip address:")
 dest_port = int(input("Please enter the other side'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 sockets
 upd_socket = (socket.AF_INET, socket.SOCK_DGRAM)
 # Binding information
 upd_socket.bind("", 7788)
 # Loops to get things done
 while True:
  send_msg(upd_socket)
  recv_msg(upd_socket)
if __name__ == "__main__":
 main()

To give you a recommended format for writing code, like this, we first build the basic framework

def main():
 pass
 # 1. Create sockets
 # 2. Bind local information
 # 3. Know the destination address and port number
 # 4. Receive data and display
 # 5. Close the socket
if __name__ == "__main__":
 main()

1. This is the basic steps, we first conceptualized a good, then we began to write representatives. Code is relatively fixed, we need to question is that we send and receive data, is the use of utf-8 or gbk problem, assuming that we are linux system, the target is the Windows system, then we need to use the data we send .encode ("gbk") for encoding and when we receive the data, it is .decode("gbk") to decode, so that we can correctly receive Chinese characters.

2. Then, in order to make our main program look clearer, we will send and receive messages, wrapped into two functions, respectively. def send_msg(upd_socket): cap (a poem)def recv_msg(upd_socket): Note that whenever we create a new function, we must think about whether the function needs parameters or not.

3. You may see at the end that I didn't write udp_socket.close() to close the socket, because as we'll see at the end, we don't need to call close.

4. In pyhton, when we use a loop, don't write 1, write True.

For more great articles on python chat feature click on the topic:Summary of python chat functions

This is the whole content of this article, I hope it will help you to learn more.