我正在嘗試使用QTcpSocket和QTcpServer編寫聊天。 我的代碼QTcpSocket連接
客戶
ChatClient::ChatClient(QObject *parent)
: QObject(parent) {
connect(&tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(error(QAbstractSocket::SocketError)));
connect(&tcpSocket, SIGNAL(connected()),
this, SLOT(requestForID()));
connect(&tcpSocket, SIGNAL(readyRead()),
this, SLOT(receiveMessage()));
tcpSocket.connectToHost(QHostAddress::LocalHost, PORT);
}
void ChatClient::requestForID() {
qDebug() << "Connected, requesting for ID";
QByteArray segment;
QDataStream out(segment);
out.setVersion(QDataStream::Qt_4_7);
out << (quint16)0 << ID;
out.device()->seek(0);
out << (quint16)(segment.size() - sizeof(quint16));
tcpSocket.write(segment);
}
void ChatClient::error(QAbstractSocket::SocketError error) {
qDebug() << "Socket error" << error;
}
服務器
ChatServer::ChatServer(QObject *parent)
: QObject(parent) {
if (!tcpServer.listen(QHostAddress::LocalHost, PORT)) {
qDebug() << "Unable to start the server"
<< tcpServer.errorString();
}
connect(&tcpServer, SIGNAL(newConnection()),
this, SLOT(processConnection()));
}
客戶端插座幾件永遠不會被連接。錯誤永遠不會被打印。 PORT = 6178. Runnig KUbuntu。從bash ping到localhost是成功的。 我在做什麼錯?
tcpserver和tcpClient似乎都是非指針成員變量,您似乎沒有初始化它們。 – Abhijith 2011-05-25 20:25:34
這是一個想法。我會嘗試回覆結果。 – OneMoreVladimir 2011-05-25 20:35:06
將兩者轉換爲指針並使用新的QTcp *(this)進行初始化,但仍然不起作用=( – OneMoreVladimir 2011-05-25 20:41:06