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