我有以下脚本:
import socket
import sys
import traceback
msg = socket.gethostbyname(socket.gethostname())
dest = ('<broadcast>',10100)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.sendto(msg, dest)
print "Sent."
while 1:
(buf,address)=s.recvfrom(10100)
if not len(buf):
break
print "Received from %s: %s" %(address, buf)
进而:
import socket
import traceback
import os
host = ''
port = 10100
sx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sx.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sx.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sx.bind((host,port))
while 1:
try:
message, address = sx.recvfrom(10104)
print "Got data from", address
sx.sendto("ola",address)
except (KeyboardInterrupt, SystemExit):
raise
except:
traceback.print_exc()
我在将它们都放在同一个脚本上时遇到了一些麻烦。
我只是想了解更多关于套接字等的知识,这没什么特别的。
我的想法是在每台机器(Raspberry Pi)中只有一个脚本,只要它们在同一个网络上,一个人就会知道另一个人的存在。
希望我解释得对。