首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >QTcpSocket连接

QTcpSocket连接
EN

Stack Overflow用户
提问于 2011-05-26 03:37:15
回答 1查看 7.9K关注 0票数 0

我正在试着用QTcpSocket和QTcpServer写一个聊天。我的几段代码

客户端

代码语言:javascript
复制
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;
}

服务器

代码语言:javascript
复制
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成功。我做错了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-05-26 04:24:02

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

最后,您可以构建Qt网络示例并测试它是否在您的机器上工作。如果你没有这些例子,请看这里:http://doc.qt.io/qt-5/examples-network.html (TCP的财富服务器/客户端)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6129902

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档