I'm trying to start QLocalServer in my local OSX 10.11.
I have client which tries connection to server in loop:
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;
}
When this code is running, I try to start QLocalServer in another application:
// 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?
}
...
}
Why when readyRead was called, bytes are not available?
You might be getting multiple connections, in which case the socket
variable might be pointing to a different object from the one which emits the readyRead
signal. Either use QObject::sender
to get the correct object in the slot, or use the QSignalMapper
. If you are using Qt5, you can also use a lambda function and capture the socket
object.