Qt unix域套接字服务器端读取
我正在使用Qt for unix域套接字,我有一个问题: 我希望服务器端在连接建立后立即读取从客户端发送的消息,下面是我的代码Qt unix域套接字服务器端读取,qt,sockets,unix,Qt,Sockets,Unix,我正在使用Qt for unix域套接字,我有一个问题: 我希望服务器端在连接建立后立即读取从客户端发送的消息,下面是我的代码 if (!server->listen("mySocket2")) { //lisetn for new connection close(); return; } connect(server, &QLocalServer::newConnection, this, &MainWindow::readData); 在
if (!server->listen("mySocket2")) {
//lisetn for new connection
close();
return;
}
connect(server, &QLocalServer::newConnection, this, &MainWindow::readData);
在readData函数中
QLocalSocket *clientConnection = server->nextPendingConnection();
connect(clientConnection, &QLocalSocket::disconnected,
clientConnection, &QLocalSocket::deleteLater);
connect(clientConnection,&QLocalSocket::readyRead,
this,&MainWindow::readyReadData);
QByteArray block;
block=clientConnection->readAll();
qDebug()<<block;
clientConnection->disconnectFromServer();
在readyReadData函数中
QLocalSocket *clientConnection = server->nextPendingConnection();
connect(clientConnection, &QLocalSocket::disconnected,
clientConnection, &QLocalSocket::deleteLater);
connect(clientConnection,&QLocalSocket::readyRead,
this,&MainWindow::readyReadData);
QByteArray block;
block=clientConnection->readAll();
qDebug()<<block;
clientConnection->disconnectFromServer();
QByteArray块;
block=clientConnection->readAll();
qDebug()我看不到在没有挂起连接时的任何条件处理。这种情况将导致nextPendingConnection()返回一个NULL ptr(实际上,只是一个零),这可能会也可能不会导致信号/插槽连接失败。你说得对,我确实在调试器模式下找到了NULL指针,因为我对Qt还不太熟悉,有没有关于如何处理条件的建议?提前感谢您在调用nextPendingConnection()后测试变量clientConnection。如果为零,则不要进行连接。这将防止调用readyReadData()。为了更加安全,您还可以在readyReadData()中测试clientConnection(如果它用于信号/插槽连接以外的位置)。我假设您定期调用nextPendingConnection()?我跟踪了您的注释,发现指针clientConnection在readData()函数中的nextPendingConnection()之后是有效的(不是零),但在输入readyReadData()后变为零。我只调用一次nextPendingConnection(),我应该定期调用它吗?还是客户端应该多次连接服务器端以确保clientConnection始终有效?否。如果您担心连接可能会出错,请将其他插槽连接到QLocalSocket::disconnected()信号。我不会尝试不必要的额外连接。