0

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

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(...)用于调试,检查它们是否正确连接....它们确实

4

1 回答 1

0

注意:你真的应该检查 waitForConnected() 的返回值。如果客户端无法连接到服务器,则进一步进行是没有意义的。

但我认为您的实际问题是您正在编写一个简单的 8 位字符串,例如“hallo welt\0”,但您正在使用 QDataStream 读取,它需要二进制格式(对于 QString,这意味着 unicode,长度优先),这不匹配。

于 2016-01-23T22:14:50.783 回答