QTcpSocket connection
I'm trying to write a chat using QTcpSocket and QTcpServer. Several pieces of my code
Client
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() << "Socke开发者_开发百科t error" << error;
}
Server
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()));
}
Client socket never gets connected. Error is never being printed. PORT = 6178. Runnig KUbuntu. Ping to localhost from bash is successful. What am I doing wrong?
I don't see any errors in your code, are you sure your Qt and "network" is working properly? Qt should emit an error but at least your code pieces here look correct to me. Maybe your code never gets called, add some debug messages to the methods.
At last you can build the Qt Network examples and test if that is working on your machine. If you don't have the examples take a look here: http://doc.qt.io/qt-5/examples-network.html (Fortune Server/Client for TCP)
精彩评论