1 # -*- coding:utf-8 -*- 2 # Author:Sure Feng 3 import socket 4 5 6 def send_msg(udp_socket): 7"""获取键盘数据,并将其发送给对方""" 8# 获取对方ip、端口 9dest_ip = input("请输入对方的ip")10dest_port = input("请输入对方的端口")11# 获取要发送的信息12msg = input("请输入要发送的信息")13# 按照utf8编码后,发送数据14udp_socket.sendto(msg.encode("utf-8"), (dest_ip, int(dest_port)))15 16 17 def rece_msg(udp_socket):18# 接收数据19msg = udp_socket.recvfrom(1024)20# 解码21recv_ip = msg[1]22recv_msg = msg[0].decode("utf-8")23# 显示解码后数据24print("%s:%s" % (str(recv_ip), recv_msg))25 26 27 def main():28# 创建套接字29udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)30# 绑定本地信息31udp_socket.bind(("", 9890))32while True:33 print("=" * 30)34 print("1:发送消息")35 print("2:接收消息")36 print("=" * 30)37 op_num = input("请输入要操作的功能序号:")38 39 # 根据需求调用相应的函数40 if op_num == "1":41 send_msg(udp_socket)42 elif op_num == "2":43 rece_msg(udp_socket)44 else:45 print(">>> 输入有误,请重新选择")46 47 48 # 关闭套接字49 udp_socket.close()50 51 52 if __name__ == "__main__":53print("main")54main()
如果觉得《udp_socket聊天器demo》对你有帮助,请点赞、收藏,并留下你的观点哦!