本文整理汇总了Python中PyQt5.QtNetwork.QLocalServer类的典型用法代码示例。如果您正苦于以下问题:Python QLocalServer类的具体用法?Python QLocalServer怎么用?Python QLocalServer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QLocalServer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: init_nxdrive_listener
def init_nxdrive_listener(self) -> None:
"""
Set up a QLocalServer to listen to nxdrive protocol calls.
On Windows, when an nxdrive:// URL is opened, it creates a new
instance of Nuxeo Drive. As we want the already running instance to
receive this call (particularly during the login process), we set
up a QLocalServer in that instance to listen to the new ones who will
send their data.
The Qt implementation of QLocalSocket on Windows makes use of named
pipes. We just need to connect a handler to the newConnection signal
to process the URLs.
"""
named_pipe = f"{BUNDLE_IDENTIFIER}.protocol.{os.getpid()}"
server = QLocalServer()
server.setSocketOptions(QLocalServer.WorldAccessOption)
server.newConnection.connect(self._handle_connection)
try:
server.listen(named_pipe)
log.info(f"Listening for nxdrive:// calls on {server.fullServerName()}")
except:
log.info(
f"Unable to start local server on {named_pipe}: {server.errorString()}"
)
self._nxdrive_listener = server
self.aboutToQuit.connect(self._nxdrive_listener.close)
示例2: init
def init():
"""Start listening to incoming connections."""
global _server
if _server is not None:
return
server = QLocalServer(None)
# find a free socket name to use
for name in ids():
if server.listen(name):
break
else:
# all names failed, try to contact and remove stale file if that fails
socket = QLocalSocket()
for name in ids():
socket.connectToServer(name)
if not socket.waitForConnected(10000):
QLocalServer.removeServer(name)
if server.listen(name):
break
else:
socket.disconnectFromServer()
else:
# no ids left, don't listen
return
app.aboutToQuit.connect(server.close)
server.newConnection.connect(slot_new_connection)
os.environ["FRESCOBALDI_SOCKET"] = name
_server = server
示例3: create
def create(self, name=piony.G_SOCKET_NAME):
QLocalServer.removeServer(name)
self.server = QLocalServer()
if not self.server.listen(name):
print("Error: server -- unable to start: {}."
.format(self.server.errorString()))
self.quit.emit()
self.server.newConnection.connect(self.notify)
示例4: Server
class Server(QDialog):
def __init__(self, parent=None):
super(Server, self).__init__(parent)
statusLabel = QLabel()
statusLabel.setWordWrap(True)
quitButton = QPushButton("Quit")
quitButton.setAutoDefault(False)
self.fortunes = (
"You've been leading a dog's life. Stay off the furniture.",
"You've got to think about tomorrow.",
"You will be surprised by a loud noise.",
"You will feel hungry again in another hour.",
"You might have mail.",
"You cannot kill time without injuring eternity.",
"Computers are not intelligent. They only think they are.",
)
self.server = QLocalServer()
if not self.server.listen('fortune'):
QMessageBox.critical(self, "Fortune Server",
"Unable to start the server: %s." % self.server.errorString())
self.close()
return
statusLabel.setText("The server is running.\nRun the Fortune Client "
"example now.")
quitButton.clicked.connect(self.close)
self.server.newConnection.connect(self.sendFortune)
buttonLayout = QHBoxLayout()
buttonLayout.addStretch(1)
buttonLayout.addWidget(quitButton)
buttonLayout.addStretch(1)
mainLayout = QVBoxLayout()
mainLayout.addWidget(statusLabel)
mainLayout.addLayout(buttonLayout)
self.setLayout(mainLayout)
self.setWindowTitle("Fortune Server")
def sendFortune(self):
block = QByteArray()
out = QDataStream(block, QIODevice.WriteOnly)
out.setVersion(QDataStream.Qt_4_0)
out.writeUInt16(0)
out.writeQString(random.choice(self.fortunes))
out.device().seek(0)
out.writeUInt16(block.size() - 2)
clientConnection = self.server.nextPendingConnection()
clientConnection.disconnected.connect(clientConnection.deleteLater)
clientConnection.write(block)
clientConnection.flush()
clientConnection.disconnectFromServer()
示例5: __init__
def __init__(self, socketname, parent=None):
"""Start the IPC server and listen to commands.
Args:
socketname: The socketname to use.
parent: The parent to be used.
"""
super().__init__(parent)
self.ignored = False
self._socketname = socketname
self._timer = usertypes.Timer(self, "ipc-timeout")
self._timer.setInterval(READ_TIMEOUT)
self._timer.timeout.connect(self.on_timeout)
if os.name == "nt": # pragma: no coverage
self._atime_timer = None
else:
self._atime_timer = usertypes.Timer(self, "ipc-atime")
self._atime_timer.setInterval(ATIME_INTERVAL)
self._atime_timer.timeout.connect(self.update_atime)
self._atime_timer.setTimerType(Qt.VeryCoarseTimer)
self._server = QLocalServer(self)
self._server.newConnection.connect(self.handle_connection)
self._socket = None
self._socketopts_ok = os.name == "nt"
if self._socketopts_ok: # pragma: no cover
# If we use setSocketOptions on Unix with Qt < 5.4, we get a
# NameError while listening...
log.ipc.debug("Calling setSocketOptions")
self._server.setSocketOptions(QLocalServer.UserAccessOption)
else: # pragma: no cover
log.ipc.debug("Not calling setSocketOptions")
示例6: startServer
def startServer(self) -> None:
self._single_instance_server = QLocalServer()
if self._single_instance_server:
self._single_instance_server.newConnection.connect(self._onClientConnected)
self._single_instance_server.listen("ultimaker-cura")
else:
Logger.log("e", "Single instance server was not created.")
示例7: __init__
def __init__(self, id, *argv):
super(QtSingleApplication, self).__init__(*argv)
self._id = id
self._activationWindow = None
self._activateOnMessage = False
# Is there another instance running?
self._outSocket = QLocalSocket()
self._outSocket.connectToServer(self._id)
self._isRunning = self._outSocket.waitForConnected()
if self._isRunning:
# Yes, there is.
self._outStream = QTextStream(self._outSocket)
self._outStream.setCodec("UTF-8")
else:
# No, there isn't.
self._outSocket = None
self._outStream = None
self._inSocket = None
self._inStream = None
self._server = QLocalServer()
self._server.listen(self._id)
self._server.newConnection.connect(self._onNewConnection)
示例8: __init__
def __init__(self, win_id, *argv):
logfunc = logging.info
logfunc(sys._getframe().f_code.co_name + '()')
QApplication.__init__(self, *argv)
self._id = win_id
self._activation_window = None
self._activate_on_message = False
# Is there another instance running?
self._outSocket = QLocalSocket()
self._outSocket.connectToServer(self._id)
self._isRunning = self._outSocket.waitForConnected()
self._outStream = None
self._inSocket = None
self._inStream = None
self._server = None
if self._isRunning:
# Yes, there is.
self._outStream = QTextStream(self._outSocket)
self._outStream.setCodec('UTF-8')
else:
# No, there isn't, at least not properly.
# Cleanup any past, crashed server.
error = self._outSocket.error()
logfunc(LOGVARSTR % ('self._outSocket.error()', error))
if error == QLocalSocket.ConnectionRefusedError:
logfunc('received QLocalSocket.ConnectionRefusedError; ' + \
'removing server.')
self.close()
QLocalServer.removeServer(self._id)
self._outSocket = None
self._server = QLocalServer()
self._server.listen(self._id)
self._server.newConnection.connect(self._on_new_connection)
logfunc(sys._getframe().f_code.co_name + '(): returning')
示例9: Server
class Server(QObject):
dataReceived = pyqtSignal(list)
quit = pyqtSignal()
def __init__(self):
super().__init__()
self.conn = None
self.server = None
def create(self, name=piony.G_SOCKET_NAME):
QLocalServer.removeServer(name)
self.server = QLocalServer()
if not self.server.listen(name):
print("Error: server -- unable to start: {}."
.format(self.server.errorString()))
self.quit.emit()
self.server.newConnection.connect(self.notify)
def close(self):
self.server.close()
def notify(self):
logger.info("1 new conn")
# WARNING: when multiple connections, each will overwrite previous!
self.conn = self.server.nextPendingConnection()
self.conn.readyRead.connect(self.receiveData)
self.conn.disconnected.connect(self.conn.deleteLater)
def receiveData(self):
logger.info("waits for data")
ins = QDataStream(self.conn)
ins.setVersion(QDataStream.Qt_5_0)
if ins.atEnd():
return
argv = ins.readQVariant()
logger.info("reads '%s'", str(argv))
# Must be setted up on 'show' action. Move from beginning to appropriate.
action.search_dst_window()
self.dataReceived.emit(argv)
示例10: __init__
def __init__(self, parent=None):
"""Start the IPC server and listen to commands."""
super().__init__(parent)
self._remove_server()
self._timer = usertypes.Timer(self, 'ipc-timeout')
self._timer.setInterval(READ_TIMEOUT)
self._timer.timeout.connect(self.on_timeout)
self._server = QLocalServer(self)
ok = self._server.listen(SOCKETNAME)
if not ok:
raise IPCError("Error while listening to IPC server: {} "
"(error {})".format(self._server.errorString(),
self._server.serverError()))
self._server.newConnection.connect(self.handle_connection)
self._socket = None
示例11: __init__
def __init__(self, socketname, parent=None):
"""Start the IPC server and listen to commands.
Args:
socketname: The socketname to use.
parent: The parent to be used.
"""
super().__init__(parent)
self.ignored = False
self._socketname = socketname
self._timer = usertypes.Timer(self, 'ipc-timeout')
self._timer.setInterval(READ_TIMEOUT)
self._timer.timeout.connect(self.on_timeout)
self._server = QLocalServer(self)
self._server.newConnection.connect(self.handle_connection)
self._socket = None
示例12: __init__
def __init__(self, parent=None):
super(Server, self).__init__(parent)
statusLabel = QLabel()
statusLabel.setWordWrap(True)
quitButton = QPushButton("Quit")
quitButton.setAutoDefault(False)
self.fortunes = (
"You've been leading a dog's life. Stay off the furniture.",
"You've got to think about tomorrow.",
"You will be surprised by a loud noise.",
"You will feel hungry again in another hour.",
"You might have mail.",
"You cannot kill time without injuring eternity.",
"Computers are not intelligent. They only think they are.",
)
self.server = QLocalServer()
if not self.server.listen('fortune'):
QMessageBox.critical(self, "Fortune Server",
"Unable to start the server: %s." % self.server.errorString())
self.close()
return
statusLabel.setText("The server is running.\nRun the Fortune Client "
"example now.")
quitButton.clicked.connect(self.close)
self.server.newConnection.connect(self.sendFortune)
buttonLayout = QHBoxLayout()
buttonLayout.addStretch(1)
buttonLayout.addWidget(quitButton)
buttonLayout.addStretch(1)
mainLayout = QVBoxLayout()
mainLayout.addWidget(statusLabel)
mainLayout.addLayout(buttonLayout)
self.setLayout(mainLayout)
self.setWindowTitle("Fortune Server")
示例13: test_socket_options_address_in_use_problem
def test_socket_options_address_in_use_problem(qlocalserver, short_tmpdir):
"""Qt seems to ignore AddressInUseError when using socketOptions.
With this test we verify this bug still exists. If it fails, we can
probably start using setSocketOptions again.
"""
servername = str(short_tmpdir / 'x')
s1 = QLocalServer()
ok = s1.listen(servername)
assert ok
s2 = QLocalServer()
s2.setSocketOptions(QLocalServer.UserAccessOption)
ok = s2.listen(servername)
print(s2.errorString())
# We actually would expect ok == False here - but we want the test to fail
# when the Qt bug is fixed.
assert ok
示例14: __init__
def __init__(self, args, parent=None):
"""Start the IPC server and listen to commands.
Args:
args: The argparse namespace.
parent: The parent to be used.
"""
super().__init__(parent)
self.ignored = False
self._socketname = _get_socketname(args)
self._remove_server()
self._timer = usertypes.Timer(self, 'ipc-timeout')
self._timer.setInterval(READ_TIMEOUT)
self._timer.timeout.connect(self.on_timeout)
self._server = QLocalServer(self)
ok = self._server.listen(self._socketname)
if not ok:
if self._server.serverError() == QAbstractSocket.AddressInUseError:
raise AddressInUseError(self._server)
else:
raise ListenError(self._server)
self._server.newConnection.connect(self.handle_connection)
self._socket = None
示例15: __init__
def __init__(self, id, *argv):
super(SingleApplication, self).__init__(*argv)
self._id = id
self._activationWindow = None
self._activateOnMessage = False
# Check if another instance is running?
self._outSocket = QLocalSocket()
self._outSocket.connectToServer(self._id)
self._isRunning = self._outSocket.waitForConnected()
if self._isRunning:
self._outStream = QtCore.QTextStream(self._outSocket)
self._outStream.setCodec('UTF-8')
else:
self._outSocket = None
self._outStream = None
self._inSocket = None
self._inStream = None
self._server = QLocalServer()
self._server.removeServer(self._id) # if existing after crash-exit
self._server.listen(self._id)
self._server.newConnection.connect(self._onNewConnection)