参考代码:
import socket
import threading
# 发送数据
def sendmsg(udp_socket, dest_addr):
# 让子线程去循环做这些事儿
while True:
msg = input("please enter the msg:")
udp_socket.sendto(msg.encode('utf-8'), dest_addr)
# 接收数据
def recvmsg(udp_socket):
# 让子线程去循环做这些事儿
while True:
recv_data = udp_socket.recvfrom(1024)
if recv_data:
recv_msg = recv_data[0].decode('utf-8')
print(recv_msg)
def chat():
# 1.创建套接字
udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 2.绑定信息
local_ip = "127.0.0.1"
local_port = 7789
udp_socket.bind((local_ip, local_port))
dest_ip = input("Please enter the dest ip: ")
dest_port = int(input("Please enter the dest port: ")) # 端口是int型
dest_addr = (dest_ip, dest_port)
# 3.聊天(创建两个线程去做
# 发数据
th_send = threading.Thread(target=sendmsg, args=(udp_socket, dest_addr,), name="sendmsg")
# 收数据
th_recv = threading.Thread(target=recvmsg, args=(udp_socket,), name="recvmsg")
th_send.start()
th_recv.start()
# 4.关闭套接字
udp_socket.close()
chat()
问题:
- 教程中由于结合了网络调试助手所以实现了这个功能,我的收发双方都是代码,出现了以下错误:
解决:因为创建完线程后,写了udp_socket.close(),所以子线程里当然就报错了。(将udp_socket.close()注释)
2.如何结束对话:目前的方法就是关闭cmd。(待思考好的方法,不过好像所有的聊天软件都是不聊天的时候,直接把窗口关了,所以直接把cmd关了的话,也是一个道理了。)