qt电脑间tcp通信程序怎么写
时间: 2023-10-03 20:02:26 浏览: 103
下面是一个基于Qt的简单的TCP通信程序,可以实现两台电脑之间的数据传输:
1. 首先需要在Qt中创建一个新的Qt Widgets Application项目。
2. 在主窗口中添加两个按钮,一个用于连接服务器,一个用于发送消息。
3. 在主窗口的头文件中添加以下代码:
```c++
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QTcpSocket>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_connectBtn_clicked();
void on_sendBtn_clicked();
void onMessageReceived();
private:
Ui::MainWindow *ui;
QTcpSocket *socket;
};
#endif // MAINWINDOW_H
```
4. 在主窗口的源文件中添加以下代码:
```c++
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
socket(new QTcpSocket(this))
{
ui->setupUi(this);
connect(socket, SIGNAL(readyRead()), this, SLOT(onMessageReceived()));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_connectBtn_clicked()
{
QString hostAddress = ui->hostLineEdit->text();
quint16 port = ui->portLineEdit->text().toUShort();
socket->connectToHost(hostAddress, port);
if (!socket->waitForConnected(5000))
{
QMessageBox::warning(this, tr("Warning"), tr("Failed to connect to server!"));
}
}
void MainWindow::on_sendBtn_clicked()
{
QString message = ui->messageLineEdit->text();
socket->write(message.toUtf8());
}
void MainWindow::onMessageReceived()
{
QByteArray data = socket->readAll();
ui->messageListWidget->addItem(QString::fromUtf8(data));
}
```
5. 运行程序,输入服务器地址和端口号,点击连接按钮,连接服务器。然后输入要发送的消息,点击发送按钮,即可将消息发送给服务器并显示在接收消息的列表中。
注意:这个程序只是一个简单的示例,需要根据具体的需求进行修改和优化。例如,需要对网络连接异常进行处理,需要考虑多线程等问题。