服务器头文件/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入门级别,请指教,谢谢啦