本文整理汇总了C++中QLocalSocket::connectToServer方法的典型用法代码示例。如果您正苦于以下问题:C++ QLocalSocket::connectToServer方法的具体用法?C++ QLocalSocket::connectToServer怎么用?C++ QLocalSocket::connectToServer使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QLocalSocket
的用法示例。
在下文中一共展示了QLocalSocket::connectToServer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: qt_connectToServer
void qt_connectToServer()
{
if (!qt_initialized)
return;
// Determine to which server we should connect
QString server = qt_localServerName;
if (!qt_optionWidget.isEmpty())
server = qt_optionWidget;
// Check if we are already connected
if (qt_socket.serverName() == server)
return;
// Disconnect
if (qt_socket.state() == QLocalSocket::ConnectedState)
{
qt_socket.disconnectFromServer();
qt_socket.waitForDisconnected(1000);
}
// Connect to server, or local server if not available.
qt_socket.connectToServer(server);
if (!qt_socket.waitForConnected(3000))
while (qt_socket.state() != QLocalSocket::ConnectedState)
qt_socket.connectToServer(qt_localServerName);
}
示例2: main
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QLocalSocket localSocket;
localSocket.connectToServer("bloggerQml", QIODevice::ReadOnly);
if(localSocket.waitForConnected(5000))
{
// there is already an application running
qDebug() << "Application is already running.";
QMessageBox::information(0, QObject::tr("Erro"), QObject::tr("A aplicação já está a ser executada."), QMessageBox::Ok);
return 0;
}
QLocalServer localServer;
localServer.listen("bloggerQml");
BloggerLoader bloggerloader;
bloggerloader.loadBlogsFromFile();
BloggerProxyModel model;
model.setSourceModel(bloggerloader.model());
Helper helper;
QtQuick2ApplicationViewer viewer;
viewer.rootContext()->setContextProperty("blogsModel", &model);
viewer.rootContext()->setContextProperty("helper", &helper);
viewer.rootContext()->setContextProperty("bloggerloader", &bloggerloader);
viewer.setMainQmlFile(QStringLiteral("qml/blogerQML/main.qml"));
viewer.showExpanded();
int res = app.exec();
bloggerloader.saveDB();
return res;
}
示例3: main
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
//a.removeLibraryPath(a.libraryPaths().first());
qRegisterMetaType<Song>("Song");
qRegisterMetaTypeStreamOperators<Song>("Song");
MainWindow w;
QStringList args = a.arguments();
QLocalSocket socket;
socket.connectToServer("iniTunes");
QTextStream stream(&socket);
if(socket.waitForConnected(3000))
{
stream <<QString::number(PLAY)<<endl;
stream << args.at(1) <<endl;
socket.waitForBytesWritten();
exit(0);
}
else
{
qDebug()<<"Launch";
w.show();
w.createRemote();
if(args.count()==2)
{
qDebug()<<"Open";
w.open(args.at(1));
}
}
return a.exec();
}
示例4: sendMessages
bool KNSingletonApplication::sendMessages(const QString &uniqueKey,
const QStringList &messages)
{
//Create sender client.
QLocalSocket client;
//Link to the server which is listening to the unique key.
client.connectToServer(uniqueKey, QIODevice::WriteOnly);
//If connecting failed, return false.
if(!client.waitForConnected(TimeoutLimit))
{
qDebug("Cannot connect to the local server.");
//Disconnect from the server.
client.disconnectFromServer();
return false;
}
//Generate the message data.
QByteArray messageData;
QDataStream dataWriter(&messageData, QIODevice::WriteOnly);
dataWriter << messages;
//Send the data to local server.
client.write(messageData);
//Check sending status.
if(!client.waitForBytesWritten(TimeoutLimit))
{
qDebug("Send arguments failed.");
client.disconnectFromServer();
return false;
}
//Send the arguments success.
client.disconnectFromServer();
return true;
}
示例5: QLocalSocket
CommandClient *UnixSocketCommandClient::newClient(const QStringList &args, bool reverse)
{
QVariantMap options;
options["name"] = args.value(1);
QLocalSocket *socket = new QLocalSocket();
UnixSocketCommandClient *client = new UnixSocketCommandClient;
client->setSocket(socket);
client->initialize();
connect(socket, &QLocalSocket::connected, [client, options, reverse]() {
if (reverse)
qInfo().noquote() << QString("unixsocket: Connected to %1").arg(options["name"].toString());
emit client->connected();
});
connect(socket, &QLocalSocket::disconnected, [client, options, reverse]() {
if (reverse)
qInfo().noquote() << QString("unixsocket: Disconnected from %1").arg(options["name"].toString());
emit client->disconnected();
});
connect(socket, static_cast<void(QLocalSocket::*)(QLocalSocket::LocalSocketError)>(&QLocalSocket::error), [options, reverse](QLocalSocket::LocalSocketError e) {
Q_UNUSED(e);
if (reverse)
qDebug().noquote() << QString("unixsocket: Failed to connect to %1").arg(options["name"].toString());
});
QTimer::singleShot(0, [socket, options]() {
socket->connectToServer(options["name"].toString());
});
return client;
}
示例6: 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);
res &= socket.waitForReadyRead(timeout); // wait for ack
res &= (socket.read(qstrlen(ack)) == ack);
return res;
}
示例7: main
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
// assure one application instance
QString uniqueID( HomePrism_UUID );
QLocalSocket socket;
socket.connectToServer(uniqueID);
if (socket.waitForConnected(500))
{
QMessageBox::critical(0, QObject::tr("HomePrism"),
QObject::tr("Another HomePrism is already running. Will exit now."));
return EXIT_FAILURE; // Exit already a process running
}
// some app specific params
QCoreApplication::setApplicationName( HomePrism_TITLE );
QCoreApplication::setOrganizationName("DKFZ");
// start
HomePrism homePrismWindow;
homePrismWindow.setGeometry(
QStyle::alignedRect(
Qt::LeftToRight,
Qt::AlignCenter,
homePrismWindow.size(),
qApp->desktop()->availableGeometry()
));
homePrismWindow.show();
//HomePrism.hide();
return app.exec();
}
示例8: getKeyValue
int QmKeysPrivate::getKeyValue(const struct input_event &query) {
// Try to connect to qmkeyd.
QLocalSocket socket;
socket.connectToServer(SERVER_NAME);
if (!socket.waitForConnected(1000)) {
return -1;
}
// Query for the given key
if (socket.write((char*)&query, sizeof(query)) != sizeof(query)) {
return -1;
}
if (!socket.waitForReadyRead(1000)) {
return -1;
}
struct input_event response;
int ret = 0;
// A loop because we might receive other events as well.
do {
ret = socket.read((char*)&response, sizeof(response));
if (ret == sizeof(response)) {
if (response.type == query.type && response.code == query.code) {
break;
}
}
} while (ret == sizeof(response));
socket.disconnect();
return response.value;
}
示例9: saveCommand
// Process incoming IPC command. First check if monero-wallet-gui is
// already running. If it is, send it to that instance instead, if not,
// queue the command for later use inside our QML engine. Returns true
// when queued, false if sent to another instance, at which point we can
// kill the current process.
bool IPC::saveCommand(QString cmdString){
qDebug() << QString("saveCommand called: %1").arg(cmdString);
QLocalSocket ls;
QByteArray buffer;
buffer = buffer.append(cmdString);
QString socketFilePath = this->socketFile().filePath();
ls.connectToServer(socketFilePath, QIODevice::WriteOnly);
if(ls.waitForConnected(1000)){
ls.write(buffer);
if (!ls.waitForBytesWritten(1000)){
qDebug() << QString("Could not send command \"%1\" over IPC %2: \"%3\"").arg(cmdString, socketFilePath, ls.errorString());
return false;
}
qDebug() << QString("Sent command \"%1\" over IPC \"%2\"").arg(cmdString, socketFilePath);
return false;
}
if(ls.isOpen())
ls.disconnectFromServer();
// Queue for later
this->SetQueuedCmd(cmdString);
return true;
}
示例10: IsAlreadyRunning
bool Application::IsAlreadyRunning () const
{
QLocalSocket socket;
socket.connectToServer (GetSocketName ());
if (socket.waitForConnected () ||
socket.state () == QLocalSocket::ConnectedState)
{
QDataStream out (&socket);
out << Arguments_;
if (socket.waitForBytesWritten ())
return true;
if (socket.error() == QLocalSocket::UnknownSocketError)
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;
}
示例11: ipcSendCommandLine
//
// Sending to the server is done synchronously, at startup.
// If the server isn't already running, startup continues,
// and the items in savedPaymentRequest will be handled
// when uiReady() is called.
//
bool PaymentServer::ipcSendCommandLine()
{
bool fResult = false;
for (const QString& r : savedPaymentRequests)
{
QLocalSocket* socket = new QLocalSocket();
socket->connectToServer(ipcServerName(), QIODevice::WriteOnly);
if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT))
{
delete socket;
socket = nullptr;
return false;
}
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << r;
out.device()->seek(0);
socket->write(block);
socket->flush();
socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT);
socket->disconnectFromServer();
delete socket;
socket = nullptr;
fResult = true;
}
return fResult;
}
示例12: listen
bool ServerCatchcopy::listen()
{
QLocalSocket socketTestConnection;
pathSocket=ExtraSocketCatchcopy::pathSocket();
socketTestConnection.connectToServer(QString::fromStdString(pathSocket));
if(socketTestConnection.waitForConnected(CATCHCOPY_COMMUNICATION_TIMEOUT))
{
error_string="Other server is listening";
emit error(error_string);
return false;
}
else
{
if(!server.removeServer(QString::fromStdString(pathSocket)))
{
error_string="Unable to remove the old server";
emit error(error_string);
}
#ifndef Q_OS_MAC
server.setSocketOptions(QLocalServer::UserAccessOption);
#endif
if(server.listen(QString::fromStdString(pathSocket)))
return true;
else
{
error_string=QStringLiteral("Unable to listen %1: %2").arg(QString::fromStdString(pathSocket)).arg(server.errorString()).toStdString();
emit error(error_string);
return false;
}
}
}
示例13: hasPrevious
bool SingleInstance::hasPrevious(const QString &name, const QStringList &args)
{
qDebug() << "Checking for previous instance...";
QLocalSocket socket;
socket.connectToServer(name, QLocalSocket::ReadWrite);
if (socket.waitForConnected())
{
qDebug() << "Connection found!";
qDebug() << "Forwarding argument to existing instance...";
QByteArray buffer;
for (auto item : args)
{
buffer.append(item+"\n");
}
qDebug() << "Forwading buffer=" << buffer;
socket.write(buffer);
return true;
}
qDebug() << socket.errorString();
qDebug() << "No connection found";
return false;
}
示例14: initLocalConnection
void MainWidget::initLocalConnection()
{
is_running = false;
QCoreApplication::setApplicationName("localserver");
QString serverName=QCoreApplication::applicationName();
QLocalSocket socket;
socket.connectToServer(serverName);
if(socket.waitForConnected(500))
{
is_running =true;
return;
}
//连接不上服务器,就创建一个
server = new QLocalServer(this);
connect(server, SIGNAL(newConnection()), this, SLOT(newLocalConnection()));
if(server->listen(serverName))
{
//防止程序崩溃时,残留进程服务,移除之
if(server->serverError() == QAbstractSocket::AddressInUseError && QFile::exists(server->serverName()))
{
QFile::remove(server->serverName());
server->listen(serverName);
}
}
}
示例15: main
int main(void)
{
QLocalSocket socket;
socket.connectToServer(SOCK_PATH);
socket.open(QIODevice::ReadWrite);
printf("Connected.\n");
char str[100];
while(printf("> "), fgets(str, 100, stdin), !feof(stdin)) {
if (socket.write(str, strlen(str)) == -1) {
perror("send");
return EXIT_FAILURE;
}
int t;
if ((t = socket.read(str, 100)) > 0) {
str[t] = '\0';
printf("echo> %s", str);
} else {
if (t < 0)
perror("recv");
else
printf("Server closed connection.\n");
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}