UDP聊天小程序+多线程(Python)
生活随笔
收集整理的這篇文章主要介紹了
UDP聊天小程序+多线程(Python)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
import socketdef send_msg(udp_socket):dest_ip=input("輸入對方ip:")dest_port=int(input("輸入對方端口:"))send_data=input("輸入消息:")udp_socket.sendto(send_data.encode("utf-8"),(dest_ip,dest_port)) # encocde為編碼
def recv_msg(udp_socket):rev_data=udp_socket.recvfrom(1024)print("%s:%s"%(str(rev_data[1]),rev_data[0].decode("utf-8"))) # decode為解碼def main():# 建立套接字udp_socket=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)# 綁定端口udp_socket.bind(('',7788))while True:# 發送消息send_msg(udp_socket)# 接收消息recv_msg(udp_socket)
if __name__ == '__main__':main()
多線程版,能同時收發消息:
import socket import threadingdef recv_msg(udp_socket):while True:recv_data=udp_socket.recvfrom(1024)print("接收到的消息:%s"%str(recv_data[0].decode("utf-8")))def send_mag(udp_socket,dest_ip,dest_port):while True:send_data=input("輸入發送的消息:")udp_socket.sendto(send_data.encode("utf-8"),(dest_ip,dest_port)) def main():udp_socket=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)udp_socket.bind(("",7890))dest_ip='輸入主機的IP地址'dest_port=8080t_recv=threading.Thread(target=recv_msg,args=(udp_socket,))t_send=threading.Thread(target=send_mag,args=(udp_socket,dest_ip,dest_port))t_recv.start()t_send.start()if __name__ == '__main__':main()總結
以上是生活随笔為你收集整理的UDP聊天小程序+多线程(Python)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 索引原理_MySQL Inn
- 下一篇: 怎么多次调用c语言dll,c-如何从注入