Python socket 广播

server

import socket

server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

server.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

connects = []

server.bind(('', 9090))

while True:
    back_msg, addr = server.recvfrom(1024)

    if addr not in connects:
        connects.append(addr)

    print(back_msg.decode("utf-8"), addr, len(connects))

    server.sendto("收到".encode('utf-8'), addr)

client

import socket
import time

client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

while True:
    client.sendto("我是设备1号".encode('utf-8'), ('', 9090))

    # data, addr = client.recvfrom(1024)
    # print("接收到数据{}:{}".format(addr,data.decode('utf-8')) )

    time.sleep(2)

你可能感兴趣的:(Python socket 广播)