qq_32556095 2016-07-18 04:15 采纳率: 0%
浏览 4041

用qt5 socket写的服务器和客户端可以连接,但客户端不能给服务器传数据

服务器头文件/widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include<QtNetwork>
class QTcpServer;
class QTcpSocket;
namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();
private slots:
    void readMessage();
    //void DataReceived();
private:
    Ui::Widget *ui;
    QTcpServer *tcpServer;
    QTcpSocket *tcpSocket;
    QString message1;
};

#endif // WIDGET_H

服务器主函数/main.cpp

 #include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

服务器源文件/widget.cpp

 #include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    tcpServer=new QTcpServer(this);
   tcpServer->listen(QHostAddress::Any,6666);

    connect(tcpServer,SIGNAL(newConnection()),this,SLOT(readMessage()));
    qDebug()<<"2";


}
Widget::~Widget()
{
    delete ui;
}
void Widget::readMessage()
{
    QTcpSocket *clientConnection=tcpServer->nextPendingConnection();
    qDebug()<<"2";
    message1=clientConnection->readAll();
    qDebug()<<message1;
    ui->statusLabel->setText(message1);
    qDebug()<<"1";
}

客户端头文件/widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include<QtNetwork>
class QTcpSocket;
namespace Ui {
class Widget;
}

class Widget : public QWidget
{
    Q_OBJECT

public:
    explicit Widget(QWidget *parent = 0);
    ~Widget();
private slots:
    void newConnect();
    void on_pushButton_clicked();

private:
    Ui::Widget *ui;
    QTcpSocket *tcpSocket;
};

#endif // WIDGET_H

客户端主函数/main.cpp

#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

客户端源文件/widget.cpp

#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    tcpSocket=new QTcpSocket(this);

}

Widget::~Widget()
{
    delete ui;
}
void Widget::newConnect()
{

    tcpSocket->abort();
    tcpSocket->connectToHost("localhost",6666);
    qDebug()<<"631";

}
void Widget::on_pushButton_clicked()
{
    newConnect();
    tcpSocket->write("2");
}

通过调试发现,服务器和客户端可以连接,但是就是不能**从客户端向服务器**发送数据,qt入门级别,请指教,谢谢啦

  • 写回答

1条回答 默认 最新

  • zqbnqsdsmd 2017-03-10 00:02
    关注
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?