1.配置
- 安装网络调试助手
- 调试网络--->检测网络是否连通,虚拟机改网络连接方式为
网络地址转换(NAT)
2.发送--->调试助手接收
from socket import *
s = socket(AF_INET,SOCK_DGRAM)# 创建一个udp的套接字
s.sendto("发送成功了".encode('gb2312'),('192.168.56.1',8080))#本地ip以及发送的端口,加码安全
s.close()
3.接收--->调试助手发送
from socket import *
s = socket(AF_INET,SOCK_DGRAM)# 创建一个udp的套接字
s.sendto("发送成功了".encode('gb2312'),('192.168.56.1',8080))
#发送
msg = s.recvfrom(1024)
print(msg)
s.close()
4.多线程聊天
from socket import *
from threading import Thread
s,ip,port = None,"",0
def send():
while True:
content = input("请输入发送内容\n")
s.sendto(content.encode("gb2312"),(ip,port))
def recv():
while True:
msg = s.recvfrom(1024)
print(ip+">>>\n "+msg[0].decode("gb2312"))
def main():
global s,port,ip
port = int(input("请输入对方端口"))
ip = input("请输入对方ip")
s = socket(AF_INET,SOCK_DGRAM)
s.bind(("",8880))#绑定端口
t = Thread(target=send)
t1 = Thread(target=recv)
t.start()
t1.start()
t.join()
if __name__ == '__main__':
main()