|
1 # -*- coding: utf-8 -*- |
|
2 |
|
3 # Copyright (c) 2010 - 2019 Detlev Offenbach <detlev@die-offenbachs.de> |
|
4 # |
|
5 |
|
6 """ |
|
7 Module implementing the cooperation server. |
|
8 """ |
|
9 |
|
10 from __future__ import unicode_literals |
|
11 |
|
12 from PyQt5.QtCore import pyqtSignal |
|
13 from PyQt5.QtNetwork import QTcpServer |
|
14 |
|
15 from .Connection import Connection |
|
16 |
|
17 import Preferences |
|
18 |
|
19 |
|
20 class CooperationServer(QTcpServer): |
|
21 """ |
|
22 Class implementing the cooperation server. |
|
23 |
|
24 @signal newConnection(connection) emitted after a new connection was |
|
25 received (Connection) |
|
26 """ |
|
27 newConnection = pyqtSignal(Connection) |
|
28 |
|
29 def __init__(self, address, parent=None): |
|
30 """ |
|
31 Constructor |
|
32 |
|
33 @param address address the server should listen on (QHostAddress) |
|
34 @param parent reference to the parent object (QObject) |
|
35 """ |
|
36 super(CooperationServer, self).__init__(parent) |
|
37 |
|
38 self.__address = address |
|
39 |
|
40 def incomingConnection(self, socketDescriptor): |
|
41 """ |
|
42 Public method handling an incoming connection. |
|
43 |
|
44 @param socketDescriptor native socket descriptor (integer) |
|
45 """ |
|
46 connection = Connection(self) |
|
47 connection.setSocketDescriptor(socketDescriptor) |
|
48 self.newConnection.emit(connection) |
|
49 |
|
50 def startListening(self, port=-1, findFreePort=False): |
|
51 """ |
|
52 Public method to start listening for new connections. |
|
53 |
|
54 @param port port to listen on (integer) |
|
55 @param findFreePort flag indicating to search for a free port |
|
56 depending on the configuration (boolean) |
|
57 @return tuple giving a flag indicating success (boolean) and |
|
58 the port the server listens on |
|
59 """ |
|
60 res = self.listen(self.__address, port) |
|
61 if findFreePort and Preferences.getCooperation("TryOtherPorts"): |
|
62 endPort = port + Preferences.getCooperation("MaxPortsToTry") |
|
63 while not res and port < endPort: |
|
64 port += 1 |
|
65 res = self.listen(self.__address, port) |
|
66 return res, port |