python中使用UDP实现网络版聊天工具

创建一个基于udp的网络程序流程很简单,具体步骤如下:

  1. 创建客户端套接字
  2. 发送/接收数据
  3. 关闭套接字

import socket

# 发送数据方法
def send_Msg(udp_socket):
    msg = input("\n please enter your data:")
    dest_ip = input("\n enter the destination ip" )
    dest_port = input('\n enter the destination port:')

    udp_socket.sendto(msg.encode('utf-8'),(dest_ip,int(dest_port)))  #注意这里端口号是int类型的,要转换下。

# 接受数据方法
def recv_Msg(udp_socket):
    recv_msgs = udp_socket.recvfrom(1024) #注意这个1024byte,大小根据需求自己设置
    mesg= recv_msgs[0].decode("utf-8")
    ip_port = recv_msgs[1]
    print("%s\n%s"%(mesg,ip_port))


def main():
    udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    udp_socket.bind(("",9525)) #  参数是个元组
    while True:
        print("***"*10)
        print("1:Send Mesg")
        print("2:Reciv Mesg")
        print("***"*10)
        choice_num = input("enter your choice num:\n")

        if choice_num == '1' :
            send_Msg(udp_socket)
        elif choice_num =='2':
            recv_Msg(udp_socket)
        else :
            print("Eroor,try again!")

#主程序执行入

if __name__ == '__main__':
    main()

启动网络调试助手,执行程序,通过在“网络调试助手”中进行通信,不过我这里是通过同一个ip进行通信的。

D:\software\python3\python.exe D:/pythoyworkspace/file_demo/Class_Demo/pachong/urllib_Request1.py
******************************
1:Send Mesg
2:Reciv Mesg
******************************
enter your choice num:1
 please enter your data:hahhahahah
 enter the destination ip192.168.1.1
 enter the destination port:9525
******************************
1:Send Mesg
2:Reciv Mesg
******************************
enter your choice num:
2
2223234343
('192.168.1.1', 9526)
******************************
1:Send Mesg
2:Reciv Mesg
******************************
enter your choice num:
2
2223234343
('192.168.1.1', 9526)
******************************

统一声明:关于原创博客内容,可能会有部分内容参考自互联网,如有原创链接会声明引用;如找不到原创链接,在此声明如有侵权请联系删除哈。关于转载博客,如有原创链接会声明;如找不到原创链接,在此声明如有侵权请联系删除哈。

发布了248 篇原创文章 · 获赞 1600 · 访问量 267万+

猜你喜欢

转载自blog.csdn.net/qq_26442553/article/details/94447479
今日推荐