from socket import *
import threading
def recv_msg(udp_socket):
"""
接收数据并显示
:return:
"""
while True:
recv_data, dest_addr = udp_socket.recvfrom(1024) #注意:recvfrom是等待接收,不需要地址
recv_data = recv_data.decode("utf-8")
print("{}:{}".format(dest_addr, recv_data))
def send_msg(udp_socket, dest_addr):
while True:
send_data = input(">").encode("utf-8")
udp_socket.sendto(send_data, dest_addr)
def main():
udp_socket = socket(AF_INET,SOCK_DGRAM) # 创建套接字
# 绑定本地信息
local_addr = ("", 8888)
udp_socket.bind(local_addr)
# 获取对方ip和port
dest_ip = input("dest ip:")
dest_port = input(input("dest port:"))
dest_addr = (dest_ip, dest_port)
t_recv = threading.Thread(target=recv_msg, args=(udp_socket,))
t_send = threading.Thread(target=send_msg, args=(udp_socket, dest_addr))
t_recv.start()
t_send.start()
if __name__ == "__main__":
main()
网友评论