嗯,我仍在尝试通过QLocalSocket运行IPC。很明显,我的套接字连接了,连接被接受了,但当我试图发送时
void ServiceConnector::send_MessageToServer(QString message) {
if(!connected){
m_socket->connectToServer(m_serverName);
m_socket->waitForConnected();
}
char str[] = {"hallo welt "};
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
函数之后立即启动,我认为这意味着它现在可以读取。。。
[edit]auto conn = connection(...)
用于调试,以检查它们是否正确连接。。。。他们做
注意:您确实应该检查waitForConnected()的返回值。如果客户端无法连接到服务器,那么继续进行下去就没有意义了。
但我认为您的实际问题是,您正在编写一个简单的8位字符串,如"hallo welt\0",但您使用的是QDataStream,它需要二进制格式(对于QString,这意味着unicode,长度优先),这不匹配。