QLocalSocket不发送任何内容

时间:2013-08-22 15:11:55

标签: c++ qt ipc qlocalsocket

好吧,我还在尝试通过QLocalSocket运行IPC。 显然我的套接字连接,连接被接受,但当我尝试发送东西时

void ServiceConnector::send_MessageToServer(QString message) {

    if(!connected){
        m_socket->connectToServer(m_serverName);
        m_socket->waitForConnected();

    }

    char str[] = {"hallo welt\0"};
    int c = m_socket->write(str,strlen(str));
    qDebug() << "written: " << c;
}

我没有得到回应......服务器的套接字什么也没做。

服务器的读取实现:

void ClientHandler::socket_new_connection() {

    logToFile("incoming connection");

    clientConnection = m_server->nextPendingConnection();

    socket_StateChanged(clientConnection->state());

    auto conn = connect(clientConnection, SIGNAL(disconnected()),this, SLOT(socket_disconnected()));
    conn = connect(clientConnection, SIGNAL(stateChanged(QLocalSocket::LocalSocketState)),this,SLOT(socket_StateChanged(QLocalSocket::LocalSocketState)));
    conn = connect(clientConnection, SIGNAL(readyRead()), this, SLOT(socket_readReady()));

    clientConnection->waitForReadyRead();
    socket_readReady();
}
void ClientHandler::socket_readReady(){
    logToFile("socket is ready to be read");

    logToFile((clientConnection->isOpen())? "open: true":"open: false");
    logToFile((clientConnection->isReadable())? "readable: true":"readable: false");

    QDataStream in(clientConnection);
    in.setVersion(QDataStream::Qt_4_0);
    if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) {
        return;
    }

    QString message;
    in >> message;

    logToFile("Message recieved" + message);

    send(message);
    emit messageReceived(message);
}

输出:

客户端:

[Debug]: ConnectingState 
[Debug]: ConnectedState 
[Debug]: socket_connected 
[Debug]: written:  10 

服务器:

[Debug]: incoming connection
[Debug]: socket is ready to be read
[Debug]: open: true
[Debug]: readable: true

套接字的readReady()信号永远不会发出,所以我决定使用

clientConnection->waitForReadyRead();
socket_readReady();

......但显然这也不起作用。在客户端的waitForReadyRead函数之后立即触发write,我认为这意味着现在可以阅读...

[编辑] auto conn = connection(...)用于调试,检查它们是否正确连接......它们是

1 个答案:

答案 0 :(得分:0)

注意:您应该检查waitForConnected()的返回值。如果客户端没有设法连接到服务器,那么继续进一步是没有意义的。

但我认为你的实际问题是你正在编写一个简单的8位字符串,例如&#34; hallo welt \ 0&#34;但你正在阅读QDataStream,它需要一个二进制格式(对于QString,这意味着unicode,长度为第一),这不匹配。