【问题标题】:Qt TCP server doesn't read data from a clientQt TCP 服务器不从客户端读取数据
【发布时间】:2020-01-28 02:45:55
【问题描述】:

我使用 Ubuntu 16.04 和 QtCreator。我编写了一个从 Raspberry Pi Zero W 接收数据的服务器。即 PC 上的服务器和 Raspberry 上的客户端。但是我的服务器不读取数据。为什么?我的代码有错误吗?

tcpserver.cpp

#include "tcpserver.h"

tcpServer::tcpServer(QObject *parent) : QObject(parent)
{
    server = new QTcpServer(this);

    connect(server, SIGNAL(newConnection()),
            this, SLOT(newConnection()));

    connect(server, SIGNAL(readyRead()),
            this, SLOT(readyRead()));

    if(!server->listen(QHostAddress::Any, 1234)){
        qDebug() << "Server could not start";
    }else{
        qDebug() << "Server started!";
    }
}

void tcpServer::newConnection(){
    socket = server->nextPendingConnection();
    qDebug() << "Client was connected!";

}

void tcpServer::readyRead(){
    QByteArray socketBuffer = socket->readAll();
    qDebug() << socketBuffer;
}

【问题讨论】:

  • 我认为你需要退后一步,学习一般的套接字和网络编程。接收数据的套接字是您在newConnection 函数中获得连接的套接字。 “服务器”套接字是被动套接字,只监听传入的连接,仅此而已。
  • 非常感谢您的评论。我了解 QTcpServer 和 QTcpSocket 的区别。

标签: c++ qt tcp server raspberry-pi


【解决方案1】:

在 tcpserver.cpp 中

connect(server, SIGNAL(newConnection()),
        this, SLOT(newConnection()));

在newConnection()中;

connect(socket, SIGNAL(readyRead()),
        this, SLOT(readyRead()));

【讨论】:

    猜你喜欢
    • 2013-03-02
    • 2021-09-05
    • 2012-09-21
    • 2012-05-26
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多