前言
QT的网络编程:
网络编程有TCP和UDP。
TCP编程需要用到两个类:QTcpServer和QTcpSocket。
目标:完成一个TCP服务器和客户端
提示:篇幅问题本文只提供部分代码,下面案例可供参考
一、服务器端
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);
tcpSocket = new QTcpSocket(this);
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(newConnection_Slot()));
}
void Widget::newConnection_Slot()
{
tcpSocket = tcpServer->nextPendingConnection();
connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readyRead_Slot()));
}
void Widget:: readyRead_Slot()
{
QString buf;
buf =tcpSocket->readAll();
ui->recvEdit->appendPlainText(buf);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_openBt_clicked()
{
tcpServer->listen(QHostAddress::Any,ui->portEdit->text().toUInt());
}
void Widget::on_closeBt_clicked()
{
tcpServer->close();
}
void Widget::on_sendBt_clicked()
{
tcpSocket->write(ui->sendEdit->text().toLocal8Bit().data());
}
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>
#include <QString>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
QTcpServer *tcpServer;
QTcpSocket *tcpSocket;
private slots:
void on_openBt_clicked();
void newConnection_Slot();
void readyRead_Slot();
void on_closeBt_clicked();
void on_sendBt_clicked();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
二、客户端
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);
tcpSocket = new QTcpSocket(this);
connect(tcpServer,SIGNAL(newConnection()),this,SLOT(newConnection_Slot()));
}
void Widget::newConnection_Slot()
{
tcpSocket = tcpServer->nextPendingConnection();
connect(tcpSocket,SIGNAL(readyRead()),this,SLOT(readyRead_Slot()));
}
void Widget:: readyRead_Slot()
{
QString buf;
buf =tcpSocket->readAll();
ui->recvEdit->appendPlainText(buf);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_openBt_clicked()
{
tcpServer->listen(QHostAddress::Any,ui->portEdit->text().toUInt());
}
void Widget::on_closeBt_clicked()
{
tcpServer->close();
}
void Widget::on_sendBt_clicked()
{
tcpSocket->write(ui->sendEdit->text().toLocal8Bit().data());
}
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>
#include <QString>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
QTcpServer *tcpServer;
QTcpSocket *tcpSocket;
private slots:
void on_openBt_clicked();
void newConnection_Slot();
void readyRead_Slot();
void on_closeBt_clicked();
void on_sendBt_clicked();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H