当前位置 博文首页 > 木木木 的博客:Qt开发之路26---TCP/IP (Socket通信)
在Qt中实现TCP/IP服务器端通信的流程:
客户端通信流程:
通过Qt提供的QTcpServer类实现服务器端的socket通信:
#ifndef TCPSERVER_H
#define TCPSERVER_H
#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>
namespace Ui {
class TcpServer;
}
class TcpServer : public QWidget
{
Q_OBJECT
public:
explicit TcpServer(QWidget *parent = 0);
~TcpServer();
private slots:
void slotNewConnection();
void slotReadyRead();
void on_pushButton_send_clicked();
private:
Ui::TcpServer *ui;
QTcpServer *m_tcpServer;//负责监听套接字
QTcpSocket *m_tcpSocket;//负责通信
};
#endif // TCPSERVER_H
#include "tcpserver.h"
#include "ui_tcpserver.h"
TcpServer::TcpServer(QWidget *parent) :
QWidget(parent),
ui(new Ui::TcpServer)
{
ui->setupUi(this);
//1.创建服务器套接字对象
m_tcpServer = new QTcpServer(this);
//2.设置为监听模式
m_tcpServer->listen(QHostAddress::Any,5200);
//3.通过信号接收客户端的请求
connect(m_tcpServer, SIGNAL(newConnection()),this,SLOT(slotNewConnection()));
}
TcpServer::~TcpServer()
{
delete ui;
}
void TcpServer::slotNewConnection()
{
//4.处理客户端请求
m_tcpSocket = m_tcpServer->nextPendingConnection();
//5.发送数据
m_tcpSocket->write("connect success!");
//6.连接信号,接受客户端数据
connect(m_tcpSocket,SIGNAL(readyRead()),this,SLOT(slotReadyRead()));
}
void TcpServer::slotReadyRead()
{
QString data = m_tcpSocket->readAll();
ui->textEdit_receiver->append(data);
}
void TcpServer::on_pushButton_send_clicked()
{
QString sendData = ui->textEdit_send->toPlainText();
m_tcpSocket->write(sendData.toLatin1());
}
客户端通过使用Qt提供的QTcpSocket类可以方便的实现与服务器端的通信:
#ifndef TCPCLIENT_H
#define TCPCLIENT_H
#include <QWidget>
#include <QTcpSocket>
namespace Ui {
class TcpClient;
}
class TcpClient : public QWidget
{
Q_OBJECT
public:
explicit TcpClient(QWidget *parent = 0);
~TcpClient();
private slots:
void slotReadyRead();
void on_pushButton_send_clicked();
private:
Ui::TcpClient *ui;
QTcpSocket *m_tcpClient;
};
#endif // TCPCLIENT_H
#include "tcpclient.h"
#include "ui_tcpclient.h"
#include <QHostAddress>
TcpClient::TcpClient(QWidget *parent) :
QWidget(parent),
ui(new Ui::TcpClient)
{
ui->setupUi(this);
//1.创建套接字
m_tcpClient = new QTcpSocket(this);
//2.连接服务器
m_tcpClient->connectToHost(QHostAddress("127.0.0.1"),5200);
//3.通过信号接收服务器数据
connect(m_tcpClient, SIGNAL(readyRead()), this, SLOT(slotReadyRead()));
}
TcpClient::~TcpClient()
{
delete ui;
}
void TcpClient::slotReadyRead()
{
QString data = m_tcpClient->readAll();
ui->textEdit_receiver->append(data);
}
void TcpClient::on_pushButton_send_clicked()
{
QString sendData = ui->textEdit_send->toPlainText();
m_tcpClient->write(sendData.toLatin1());
}
上一篇:Qt开发之路25—Socket通信
下一篇:Qt开发之路27—UDP (Socket通信)