Python服务发现:在本地网络上发布服务 [英] Python service discovery: Advertise a service across a local network

查看:254
本文介绍了Python服务发现:在本地网络上发布服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个服务器python脚本运行在一个本地网络机器上,等待客户端连接,并传递他们一些工作要做。服务器和客户端代码都已经写入,并且按预期工作...

I have a "server" python script running on one of the local network machines, which waits for clients to connect, and passes them some work to do. The server and client code have both been written, and are working as expected...

问题是,此服务器可能正在本地网络中的任何计算机上运行,所以我不能硬编码在脚本中的地址...我立即想知道我是否可以使机器广告其存在,客户可以回应。这是可行的在Python与标准库?我真的没有时间下载扭曲或龙卷风和了解他们,不幸的是,所以我需要一些简单的。

The problem is, this server might be running from any machine in the local network, so I can't hard code the address in the script... I immediately wondered if I can make a machine advertise about its existence, and clients can respond to that. Is that doable in Python with the standard library? I really don't have time to download twisted or tornado and learn about them, unfortunately, so I need something simple.

我试图想更多地了解它,并实现我可以有一个单一的静态IP机器,其中服务器注册/注销,客户端可以从那里寻找服务器。种类的像洪流跟踪器,我想。

I tried to think more about it, and realized I can have a single static IP machine where servers register/unregister from and clients can look for servers from there. Kind of like a torrent tracker, I think. This'll have to do if I can't do the service advertising approach easily.

推荐答案

简单的服务公告方式/发现 是通过广播UDP数据包。

An easy way to do service announcement/discovery on the local network is by broadcasting UDP packets.

常量: b

PORT = 50000
MAGIC = "fna349fn" #to make sure we don't confuse or get confused by other programs

公告

from time import sleep
from socket import socket, AF_INET, SOCK_DGRAM, SOL_SOCKET, SO_BROADCAST, gethostbyname, gethostname

s = socket(AF_INET, SOCK_DGRAM) #create UDP socket
s.bind(('', 0))
s.setsockopt(SOL_SOCKET, SO_BROADCAST, 1) #this is a broadcast socket
my_ip= gethostbyname(gethostname()) #get our IP. Be careful if you have multiple network interfaces or IPs

while 1:
    data = MAGIC+my_ip
    s.sendto(data, ('<broadcast>', PORT))
    print "sent service announcement"
    sleep(5)

发现

Discovery:

from socket import socket, AF_INET, SOCK_DGRAM

s = socket(AF_INET, SOCK_DGRAM) #create UDP socket
s.bind(('', PORT))

while 1:
    data, addr = s.recvfrom(1024) #wait for a packet
    if data.startswith(MAGIC):
        print "got service announcement from", data[len(MAGIC):]

此代码改编自 demo on python.org

这篇关于Python服务发现:在本地网络上发布服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆