- socket通信分为server端与client端,基于tcp的需要首先建立server-client的连接,然后才能通信。
- 客户端程序如下:
- 在QT上建立一个widget界面程序,在界面中添加一个button和LineEdite,分别命名为sendButton、inputLine;LineEdit是客户端输入,点击button发送输入内容。
- 在工程文件中加入 QT +=network
- 客户端的mywidget.h
- #ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
#include <QtNetwork>
namespace Ui {
class myWidget;
}
class myWidget : public QWidget
{
Q_OBJECT
public:
explicit myWidget(QWidget *parent = 0);
~myWidget();
private:
Ui::myWidget *ui;
QTcpSocket *client;
const char *data;
private slots:
void senddata();
};
#endif // MYWIDGET_H
- 客户端的mywidget.cpp
- :#include "mywidget.h"
#include "ui_mywidget.h"
myWidget::myWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::myWidget)
{
ui->setupUi(this);
client = new QTcpSocket(this);
client->connectToHost(QHostAddress("10.9.3.95"),5000);
connect(ui->sendButton,SIGNAL(clicked()),this,SLOT(senddata()));
}
myWidget::~myWidget()
{
delete ui;
}
void myWidget::senddata()
{
data=ui->inputLine->text().toStdString().c_str();
client->write(data);
ui->inputLine->setText("send ok!");
} - 服务端:服务端本程序中只用来接收客户端发送来的消息,在server的界面中添加一个label用来提示是否有客户端连接;添加一个LineEdit用来输出服务端接收到的
- 消息。在工程中添加QT +=network
- 服务端程序:
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>
namespace Ui {
class mywidget;
}
class mywidget : public QWidget
{
Q_OBJECT
public:
explicit mywidget(QWidget *parent = 0);
~mywidget();
private:
Ui::mywidget *ui;
QTcpServer *server;
QTcpSocket *clientConnection;
char recbuf[1024];
private slots:
void acceptConnection();
void readClient();
};
#endif // MYWIDGET_H
- #include "mywidget.h"
#include "ui_mywidget.h"
mywidget::mywidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::mywidget)
{
ui->setupUi(this);
server=new QTcpServer();
clientConnection=new QTcpSocket();
server->listen(QHostAddress::Any,5000);
connect(server,SIGNAL(newConnection()),this,SLOT(acceptConnection()));
}
mywidget::~mywidget()
{
delete ui;
}
void mywidget::acceptConnection()
{
clientConnection=server->nextPendingConnection();
ui->label->setText("connect....");
connect(clientConnection,SIGNAL(readyRead()),this,SLOT(readClient()));
}
void mywidget::readClient()
{
memset(recbuf,0,sizeof(recbuf));
clientConnection->read(recbuf,1024);
ui->recLine->clear();
ui->recLine->setText(recbuf);
}
qt tcp socket简单的通信程序
最新推荐文章于 2024-07-05 19:03:07 发布
本文介绍了如何使用QT库创建TCP Socket通信程序,包括客户端和服务器端的实现。客户端通过QTcpSocket连接到服务器,并在按钮触发时发送LineEdit中的文本。服务器端通过QTcpServer监听连接,接收到客户端消息后显示在界面上。
摘要由CSDN通过智能技术生成