本文整理汇总了C++中QLocalSocket类的典型用法代码示例。如果您正苦于以下问题:C++ QLocalSocket类的具体用法?C++ QLocalSocket怎么用?C++ QLocalSocket使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QLocalSocket类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: ENTER
void
CommandSender::sendToServer( const int profileId, const CliOptions& options )
{
ENTER()(profileId)(options);
QString uname = qgetenv( "USER" ); // UNIX
if( uname.isEmpty() )
uname = qgetenv( "USERNAME" ); // Windows
QString serverName = QString("redtimer-%1-%2").arg(uname).arg(profileId);
DEBUG()(serverName);
QLocalSocket* socket = new QLocalSocket( this );
sockets_.insert( socket, true );
connect( socket, &QLocalSocket::connected, [=](){ sendToSocket(socket, options); } );
connect( socket, &QLocalSocket::disconnected, [=](){ deleteSocket(socket); } );
socket->connectToServer( serverName, QIODevice::ReadWrite );
if( !socket->waitForConnected() )
deleteSocket( socket );
RETURN();
}
示例2: connect
void ApplicationCore::slotHandleUniqueApplicationConnection()
{
QLocalSocket *socket = m_uniqueApplicationServer.nextPendingConnection();
connect(socket, &QLocalSocket::readyRead, socket, [this, socket](){
if (!socket->canReadLine())
return;
while (socket->canReadLine()) {
const QByteArray data = socket->readLine().trimmed();
if (data.startsWith(StartTaskCommand)) {
bool ok = true;
const TaskId id = data.mid(StartTaskCommand.length()).toInt(&ok);
if (ok) {
m_timeTracker.slotStartEvent(id);
} else {
qWarning() << "Received invalid argument:" << data;
}
} else if (data.startsWith(RaiseWindowCommand)) {
// nothing to do, see below
}
}
socket->deleteLater();
showMainWindow(ApplicationCore::ShowMode::ShowAndRaise);
});
}
示例3: log
void Server::onNewConnection()
{
QLocalSocket* socket = m_server->nextPendingConnection();
if (!socket) {
log("No pending client connections!", LogError);
} else if ( socket->state() != QLocalSocket::ConnectedState ) {
log("Client is not connected!", LogError);
socket->deleteLater();
} else {
QScopedPointer<ClientSocket> clientSocket( new ClientSocket(socket) );
const Arguments args = clientSocket->readArguments();
if ( !args.isEmpty() ) {
++m_socketCount;
connect( clientSocket.data(), SIGNAL(destroyed()),
this, SLOT(onSocketClosed()) );
connect( this, SIGNAL(destroyed()),
clientSocket.data(), SLOT(close()) );
connect( this, SIGNAL(destroyed()),
clientSocket.data(), SLOT(deleteAfterDisconnected()) );
emit newConnection( args, clientSocket.take() );
}
}
}
示例4: sendMessage
bool GUISingleApplication::sendMessage(const QByteArray &message, int timeout)
{
QLocalSocket socket;
bool connected = false;
for(int i = 0; i < 2; i++) {
socket.connectToServer(d_ptr->serverName);
connected = socket.waitForConnected(timeout/2);
if (connected || i > 0)
break;
int ms = 250;
#if defined(Q_OS_WIN)
Sleep(DWORD(ms));
#else
usleep(ms*1000);
#endif
}
if (!connected)
return false;
QDataStream ds(&socket);
ds << message;
socket.waitForBytesWritten(timeout);
return true;
}
示例5: listen
bool ServerCatchcopy::listen()
{
QLocalSocket socketTestConnection;
pathSocket=ExtraSocketCatchcopy::pathSocket();
socketTestConnection.connectToServer(pathSocket);
if(socketTestConnection.waitForConnected(CATCHCOPY_COMMUNICATION_TIMEOUT))
{
error_string="Other server is listening";
emit error(error_string);
return false;
}
else
{
server.removeServer(pathSocket);
if(server.listen(pathSocket))
return true;
else
{
error_string=QString("Unable to listen %1: %2").arg(pathSocket).arg(server.errorString());
emit error(error_string);
return false;
}
}
}
示例6: RK_TRACE
RKGraphicsDeviceBackendTransmitter* RKGraphicsDeviceBackendTransmitter::instance () {
if (_instance) return _instance;
RK_TRACE (GRAPHICS_DEVICE);
QLocalSocket *con = new QLocalSocket ();
con->connectToServer (RKRBackendProtocolBackend::rkdServerName ());
con->waitForConnected (2000);
if (con->state () == QLocalSocket::ConnectedState) {
con->write (RKRBackendTransmitter::instance ()->connectionToken ().toLocal8Bit ().data ());
con->write ("\n");
con->waitForBytesWritten (1000);
_instance = new RKGraphicsDeviceBackendTransmitter (con, true);
return _instance;
}
return 0;
}
示例7: sendMessage
bool QtLocalPeer::sendMessage(const QString& message, int timeout)
{
if(!isClient())
{
return false;
}
QLocalSocket socket;
bool connOk = false;
for(int i = 0; i < 2; i++)
{
// Try twice, in case the other instance is just starting up
socket.connectToServer(socketName);
connOk = socket.waitForConnected(timeout / 2);
if(connOk || i)
{
break;
}
int ms = 250;
#if defined(Q_OS_WIN)
Sleep(DWORD (ms));
#else
struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
nanosleep(&ts, NULL);
#endif
}
if(!connOk)
{
return false;
}
QByteArray uMsg(message.toUtf8());
QDataStream ds(&socket);
ds.writeBytes(uMsg.constData(), uMsg.size());
bool res = socket.waitForBytesWritten(timeout);
if(res)
{
res &= socket.waitForReadyRead(timeout); // wait for ack
if(res)
{
res &= (socket.read(qstrlen(ack)) == ack);
}
}
return res;
}
示例8: out
bool Application::IsAlreadyRunning () const
{
QLocalSocket socket;
socket.connectToServer (GetSocketName ());
if (socket.waitForConnected () ||
socket.state () == QLocalSocket::ConnectedState)
{
QByteArray toSend;
{
QDataStream out (&toSend, QIODevice::WriteOnly);
out << Arguments_;
}
socket.write (toSend);
socket.disconnectFromServer ();
socket.waitForDisconnected ();
return true;
}
else
{
switch (socket.error ())
{
case QLocalSocket::ServerNotFoundError:
case QLocalSocket::ConnectionRefusedError:
break;
default:
qWarning () << Q_FUNC_INFO
<< "socket error"
<< socket.error ();
return true;
}
}
// Clear any halted servers and their messages
QLocalServer::removeServer (GetSocketName ());
return false;
}
示例9: main
int main(int argc, char *argv[])
{
#if QT_NO_DEBUG
QLocalSocket socket;
socket.connectToServer(SERVER);
if(socket.waitForConnected(1000))
{
if (argc == 2)
{
socket.write(argv[1]);
socket.flush();
socket.waitForBytesWritten();
}
socket.disconnectFromServer();
exit(0);
}
else
{
if (argc != 1)
exit(0);
}
#endif
QApplication a(argc, argv);
MainWindow w;
QTranslator translator ;
translator.load("/usr/share/qt/translations/qt_cs");
a.installTranslator(&translator);
//w.show();
return a.exec();
}
示例10: receiveConnection
void QtLocalPeer::receiveConnection()
{
QLocalSocket* socket = server->nextPendingConnection();
if (!socket)
return;
// Why doesn't Qt have a blocking stream that takes care of this shait???
while (socket->bytesAvailable() < static_cast<int>(sizeof(quint32))) {
if (!socket->isValid()) // stale request
return;
socket->waitForReadyRead(1000);
}
QDataStream ds(socket);
QByteArray uMsg;
quint32 remaining;
ds >> remaining;
uMsg.resize(remaining);
int got = 0;
char* uMsgBuf = uMsg.data();
//qDebug() << "RCV: remaining" << remaining;
do {
got = ds.readRawData(uMsgBuf, remaining);
remaining -= got;
uMsgBuf += got;
//qDebug() << "RCV: got" << got << "remaining" << remaining;
} while (remaining && got >= 0 && socket->waitForReadyRead(2000));
//### error check: got<0
if (got < 0) {
qWarning() << "QtLocalPeer: Message reception failed" << socket->errorString();
delete socket;
return;
}
// ### async this
QString message = QString::fromUtf8(uMsg.constData(), uMsg.size());
socket->write(ack, qstrlen(ack));
socket->waitForBytesWritten(1000);
emit messageReceived(message, socket); // ##(might take a long time to return)
}
示例11: receiveConnection
void QtLocalPeer::receiveConnection()
{
QLocalSocket* socket = server->nextPendingConnection();
if(!socket)
{
return;
}
while(socket->bytesAvailable() < (int) sizeof(quint32))
{
socket->waitForReadyRead();
}
QDataStream ds(socket);
QByteArray uMsg;
quint32 remaining;
ds >> remaining;
uMsg.resize(remaining);
int got = 0;
char* uMsgBuf = uMsg.data();
do
{
got = ds.readRawData(uMsgBuf, remaining);
remaining -= got;
uMsgBuf += got;
}
while(remaining && got >= 0 && socket->waitForReadyRead(2000));
if(got < 0)
{
qWarning("QtLocalPeer: Message reception failed %s", socket->errorString().toLatin1().constData());
delete socket;
return;
}
QString message(QString::fromUtf8(uMsg));
socket->write(ack, qstrlen(ack));
socket->waitForBytesWritten(1000);
delete socket;
emit messageReceived(message); //### (might take a long time to return)
}
示例12: QFileInfo
bool mASocketManager::openFileOnRemote(const QString &_path)
{
bool r = false;
QString path = QFileInfo(_path).canonicalFilePath();
path.append('\n');
QLocalSocket socket;
socket.connectToServer(MA_LOCAL_SERVER_NAME);
if(socket.waitForConnected(MAX_TIMEOUT_CLIENT))
{
socket.write(path.toUtf8());
socket.flush();
socket.waitForBytesWritten(MAX_TIMEOUT_CLIENT);
r = true;
}
socket.close();
return r;
}
示例13: loadFile
void SocketExternalInstance::loadFile(const QString &file_name) const
{
#ifdef _WIN32
::AllowSetForegroundWindow(-1);
#endif
QLocalSocket socket;
socket.connectToServer(GLOG_SERVICE_NAME);
if (!socket.waitForConnected(1000)) {
LOG( logERROR ) << "Failed to connect to socket";
return;
}
socket.write(file_name.toUtf8());
if (!socket.waitForBytesWritten(1000)) {
LOG( logERROR ) << "Failed to send filename";
}
socket.close();
}
示例14: clientConnected
AuthorizationRecord QJsonUIDAuthority::clientConnected(QJsonStream *stream)
{
AuthorizationRecord authRecord;
authRecord.state = QJsonAuthority::StateNotAuthorized;
if (!stream)
return authRecord;
QLocalSocket *socket = qobject_cast<QLocalSocket*>(stream->device());
if (!socket)
return authRecord;
if (socket->socketDescriptor() == (qintptr)-1) {
qWarning() << Q_FUNC_INFO << "no socket descriptor available for connection" << socket;
return authRecord;
}
uid_t euid;
#if defined(Q_OS_MAC)
gid_t egid;
if (::getpeereid(socket->socketDescriptor(), &euid, &egid) != 0) {
qWarning() << "getpeereid failed with errcode" << errno << socket->socketDescriptor();
return authRecord;
}
#else
// Check the UID table and return Authorized if appropriate.
struct ucred cr;
socklen_t len = sizeof(struct ucred);
if (::getsockopt(socket->socketDescriptor(), SOL_SOCKET, SO_PEERCRED, &cr, &len) != 0) {
qWarning() << "getsockopt failed with errcode" << errno << socket->socketDescriptor();
return authRecord;
}
euid = cr.uid;
#endif
if (m_nameForUid.contains(euid)) {
authRecord.identifier = m_nameForUid.value(euid);
authRecord.state = StateAuthorized;
}
return authRecord;
}
示例15: sendRaiseRequest
bool Application::sendRaiseRequest()
{
if (!d_ptr->isRunning)
return false;
QLocalSocket localSocket;
localSocket.connectToServer(GUI_APPLICATION_SHARED_MEMORY_KEY, QIODevice::WriteOnly);
if (!localSocket.waitForConnected(GUI_APPLICATION_LOCAL_SOCKET_TIMEOUT))
return false;
localSocket.write(QString("raise").toUtf8());
if (!localSocket.waitForBytesWritten(GUI_APPLICATION_LOCAL_SOCKET_TIMEOUT))
return false;
localSocket.disconnectFromServer();
return true;
}