gpt4 book ai didi

c++ - 当字节不可用时,QLocalServer 发出 readyRead

转载 作者:行者123 更新时间:2023-11-28 05:41:49 25 4
gpt4 key购买 nike

我正在尝试在本地 OSX 10.11 中启动 QLocalServer。

我有客户端尝试循环连接到服务器:

int connect(const char* filename) {
int sock;
struct sockaddr_un serv_addr;

memset(&serv_addr, 0x00, sizeof(serv_addr));
serv_addr.sun_family = AF_LOCAL;
strncpy(serv_addr.sun_path, filename, sizeof(serv_addr.sun_path) - 1);

if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
return sock;
}

if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1) {
close(sock);
sock = -1;
return sock;
}

return sock;
}

int main() {
int sock;
while((sock = connect("my_socket_server")) == -1) {
usleep(3000);
}

// The code never reaches this line

const char* buffer = "hello";
if (send(sock, buffer, strlen(buffer), 0) < 0) {
exit(1);
}

return 0;
}

当这段代码运行时,我尝试在另一个应用程序中启动 QLocalServer:

// Starting server:

QString socket_path = "my_socket_server";
QLocalServer::removeServer(socket_path);
if (!server.listen(socket_path)) {
return false;
}

connect(&server, &QLocalServer::newConnection, this, &MyServerClass::newConnection);

...

void MyServerClass::newConnection() {
socket = server.nextPendingConnection(); // socket - member of MyServerClass
connect(socket, &QLocalSocket::disconnected, socket, &QLocalSocket::deleteLater);
connect(socket, &QLocalSocket::readyRead, this, &MyServerClass::readyRead);
}

...

void MyServerClass::readyRead() {
if (!socket->bytesAvailable()) {
exit(1); // THIS CODE WAS CALLED. WHY?
}

...
}

为什么调用readyRead时,bytes不可用?

最佳答案

您可能获得多个连接,在这种情况下,socket 变量可能指向与发出 readyRead 信号的对象不同的对象。要么使用 QObject::sender在插槽中获取正确的对象,或使用 QSignalMapper .如果您使用的是 Qt5,您还可以使用 lambda 函数并捕获 socket 对象。

关于c++ - 当字节不可用时,QLocalServer 发出 readyRead,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36934662/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com