不为别的,只为做一个连自己都羡慕的人

python建立连接,获取动态地址,有缺陷

client.py

'''客户端'''

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

PORT = 1060

s.bind(('', PORT))
print('Listening for broadcast at ', s.getsockname())

while True:
    data, address = s.recvfrom(65535)
    print('Server received from {}:{}'.format(address, data.decode('utf-8')))

server.py

'''服务端'''

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

PORT = 1060

network = '<broadcast>'
s.sendto('Client broadcast message!'.encode('utf-8'), (network, PORT))

此方法也能够建立长连接,但是是客户端启动,服务端每运行一次,客户端获取一次动态ip

posted @ 2020-12-21 14:39  升级打怪  阅读(117)  评论(0编辑  收藏  举报