【问题标题】:QTcpSocket connectionQTcpSocket 连接
【发布时间】:2011-05-25 19:37:14
【问题描述】:

我正在尝试使用 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 是成功的。 我做错了什么?

【问题讨论】:

  • tcpserver 和 tcpClient 似乎都是非指针成员变量,你似乎没有初始化它们。
  • 这是一个想法。我会尝试回复结果。
  • 都转换为指针并用新的QTcp*(this)初始化,但还是不行=(
  • @Abhijith - 这根本不重要......他们将使用 ChatClient/Server 类初始化,使用默认构造函数进行初始化:QTcpSocket(QObject * parent = NULL) 和 QTcpServer(QObject * parent =空)。
  • @OneMoreVladimir 你能为客户端/服务器提供更多代码吗?也许问题在于您的代码中的其他地方。

标签: qt


【解决方案1】:

我在您的代码中没有看到任何错误,您确定您的 Qt 和“网络”工作正常吗? Qt 应该会发出错误,但至少您的代码片段在我看来是正确的。也许你的代码永远不会被调用,在方法中添加一些调试消息。

最后,您可以构建 Qt 网络示例并测试它是否在您的机器上运行。如果您没有示例,请看这里:http://doc.qt.io/qt-5/examples-network.html (Fortune Server/Client for TCP)

【讨论】:

  • 感谢您回复 Xander。我已经构建了tripplanner 和tripserver 示例(来自Programming Qt GUI 4)并且它们确实有效,唯一的区别是tripserver 使用的是QTcpSocket 而不是QTcpServer。根据doc.qt.nokia.com/4.7/network-fortuneserver.html,我也没有看到任何错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-22
  • 2017-06-21
相关资源
最近更新 更多