Server: add a socket listener, able to accept client on Unix or TCP socket

This commit is contained in:
nemunaire 2015-05-19 12:32:23 +02:00
parent c94d9743dd
commit 6c244cffa0

View File

@ -117,3 +117,70 @@ class SocketServer(AbstractServer):
for line in temp:
yield line
class SocketListener(AbstractServer):
def __init__(self, new_server_cb, id, sock_location=None, host=None, port=None, ssl=None):
self.id = id
AbstractServer.__init__(self)
self.new_server_cb = new_server_cb
self.sock_location = sock_location
self.host = host
self.port = port
self.ssl = ssl
self.nb_son = 0
def fileno(self):
return self.socket.fileno() if self.socket else None
@property
def connected(self):
"""Indicator of the connection aliveness"""
return self.socket is not None
def _open(self):
import os
import socket
self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
if self.sock_location is not None:
try:
os.remove(self.sock_location)
except FileNotFoundError:
pass
self.socket.bind(self.sock_location)
elif self.host is not None and self.port is not None:
self.socket.bind((self.host, self.port))
self.socket.listen(5)
return True
def _close(self):
import os
import socket
try:
self.socket.shutdown(socket.SHUT_RDWR)
self.socket.close()
if self.sock_location is not None:
os.remove(self.sock_location)
except socket.error:
pass
# Read
def read(self):
if not self.connected:
return []
conn, addr = self.socket.accept()
self.nb_son += 1
ss = SocketServer(id=self.id + "#" + str(self.nb_son), socket=conn)
self.new_server_cb(ss)
return []