我正在试着用QTcpSocket和QTcpServer写一个聊天。我的几段代码
客户端
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()));
}客户端套接字永远不会连接。从不打印错误。端口= 6178。运行KUbuntu。从bash Ping localhost成功。我做错了什么?
发布于 2011-05-26 04:24:02
我在你的代码中没有看到任何错误,你确定你的Qt和"network“工作正常吗?Qt应该会发出一个错误,但至少你的代码片段在我看来是正确的。也许你的代码永远不会被调用,在方法中添加一些调试消息。
最后,您可以构建Qt网络示例并测试它是否在您的机器上工作。如果你没有这些例子,请看这里:http://doc.qt.io/qt-5/examples-network.html (TCP的财富服务器/客户端)
https://stackoverflow.com/questions/6129902
复制相似问题