亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有沒有辦法模擬網絡,以便我可以測試用 python 編寫的 p2p 網絡代碼?

有沒有辦法模擬網絡,以便我可以測試用 python 編寫的 p2p 網絡代碼?

青春有我 2023-07-18 10:18:20
我需要能夠在網絡的每個“節點”上運行 python 代碼,以便我可以正確測試代碼。我無法使用不同的端口號并運行代碼,因為我需要處理各種其他事情,這些事情強制使用唯一的 IP 地址。
查看完整描述

2 回答

?
holdtom

TA貢獻1805條經驗 獲得超10個贊

在我的 DHT p2p 項目中,我有一個抽象網絡通信的特定對象。在測試過程中,我使用在內存中操作的對象來模擬該對象:


class MockProtocol:


    def __init__(self, network, peer):

        self.network = network

        self.peer = peer


    async def rpc(self, address, name, *args):

        peer = self.network.peers[address[0]]

        proc = getattr(peer, name)

        start = time()

        out = await proc((self.peer._uid, None), *args)

        delta = time() - start

        assert delta < 5, "RPCProtocol allows 5s delay only"

        return out



class MockNetwork:


    def __init__(self):

        self.peers = dict()


    def add(self, peer):

        peer._protocol = MockProtocol(self, peer)

        self.peers[peer._uid] = peer


    def choice(self):

        return random.choice(list(self.peers.values()))



async def simple_network():

    network = MockNetwork()

    for i in range(5):

        peer = make_peer()

        network.add(peer)

    bootstrap = peer

    for peer in network.peers.values():

        await peer.bootstrap((bootstrap._uid, None))

    for peer in network.peers.values():

        await peer.bootstrap((bootstrap._uid, None))


    # run connect, this simulate the peers connecting to an existing

    # network.

    for peer in network.peers.values():

        await peer.connect()


    return network


@pytest.mark.asyncio

async def test_dict(make_network):

    network = await make_network()

    # setup

    value = b'test value'

    key = peer.hash(value)

    # make network and peers

    one = network.choice()

    two = network.choice()

    three = network.choice()

    four = network.choice()


    # exec

    out = await three.set(value)


    # check

    assert out == key


    fallback = list()

    for xxx in (one, two, three, four):

        try:

            out = await xxx.get(key)

        except KeyError:

            fallback.append(xxx)

        else:

            assert out == value


    for xxx in fallback:

        log.warning('fallback for peer %r', xxx)

        out = await xxx.get_at(key, three._uid)

        assert out == value


查看完整回答
反對 回復 2023-07-18
?
POPMUISE

TA貢獻1765條經驗 獲得超5個贊

我認為 vmware 或 virtual box 可以幫助你。



查看完整回答
反對 回復 2023-07-18
  • 2 回答
  • 0 關注
  • 161 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號