Write to socket from multiple coroutine asynchronously.

47 views
Skip to first unread message

huangyi

unread,
Dec 22, 2017, 3:43:59 AM12/22/17
to gevent: coroutine-based Python network library
In long connection game servers, most sockets need to be write in multiple coroutines, and hopefully asynchronously. So I create a coroutine dedicated to writing to the socket:

import gevent.queue
def _writer(sock, queue):
   
for item in queue:
        sock
:sendall(item)


class asyncsocket(socket):
   
def __init__(self, *args, **kwargs):
        socket
.__init__(self, *args, **kwargs)
        queue
= gevent.queue.Queue()
       
self._queue = queue
       
self._writer = gevent.spawn(_writer, self, queue)


   
def sendall(self, msg):
       
self._queue.put(msg)



Now i wonder is it too wasteful, if there is a low level api, maybe we can save the cost of extra coroutine?

huangyi

unread,
Dec 22, 2017, 3:57:01 AM12/22/17
to gevent: coroutine-based Python network library
在 2017年12月22日星期五 UTC+8下午4:43:59,huangyi写道:
Sorry for the temporarily buggy code, it should be like his:
import gevent.queue
def _writer(sock, queue):
    for item in queue:
        sock.sendall(item)

class asyncsocket(object):
    def __init__(self, sock):
        self._sock = sock
        self._queue = gevent.queue.Queue()
        self._writer = gevent.spawn(_writer, self._sock, self._queue)

    def sendall(self, msg):
        self._queue.put(msg)

    def close(self):
        self._writer.kill()


Reply all
Reply to author
Forward
0 new messages