V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
woshichuanqilz
V2EX  ›  Python

socket server Python 服务端如何主动发送消息?

  •  
  •   woshichuanqilz · 2019-05-23 11:56:40 +08:00 · 2330 次点击
    这是一个创建于 1772 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我查看了这里的资料, 看到 server 发送消息都是在 handle 里面也就是说要先有客户端有消息发送过来才会做出对应的发送消息的动作, 那么如果我想在服务端主动的发送消息给客户端这个应该怎么做? https://docs.python.org/3/library/socketserver.html#socketserver.BaseServer.server_bind

    这个是实例代码, 这个 handle 里面处理了消息发送的过程。

    import socketserver
    
    class MyUDPHandler(socketserver.BaseRequestHandler):
        """
        This class works similar to the TCP handler class, except that
        self.request consists of a pair of data and client socket, and since
        there is no connection the client address must be given explicitly
        when sending data back via sendto().
        """
    
        def handle(self):
            data = self.request[0].strip()
            socket = self.request[1]
            print("{} wrote:".format(self.client_address[0]))
            print(data)
            socket.sendto(data.upper(), self.client_address)
    
    if __name__ == "__main__":
        HOST, PORT = "localhost", 9999
        with socketserver.UDPServer((HOST, PORT), MyUDPHandler) as server:
            server.serve_forever()
    
    
    3 条回复    2019-05-23 14:11:44 +08:00
    prim
        1
    prim  
       2019-05-23 12:15:54 +08:00
    建议你看看 TCP
    如果非要用 UDP 的话,你就可以在第一次收到这个 client address 的时候把这个 socket 和 address 存起来
    你想在哪里主动发数据的话就再用前面记录下来的 socket 和 address

    如果你是想在 client 没有发包过来的时候就发包给他
    那么你把这个 client 实现成你代码里面的 UDPServer 就好了,这样你就能提前这个 client address
    xomix
        2
    xomix  
       2019-05-23 13:00:51 +08:00
    这是一个很常见的问题,百度关键字 udp 打洞。
    至于怎么做你自己百度吧。
    julyclyde
        3
    julyclyde  
       2019-05-23 14:11:44 +08:00
    socketserver 里对于 TCP 协议,所谓“消息”是指一个连接
    对于 UDP 协议,当然必须先收到消息才能确定角色。如果没收到就发,那叫客户端不叫服务器
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3358 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 10:43 · PVG 18:43 · LAX 03:43 · JFK 06:43
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.