一、简介
QTcpServer Class
The QTcpServer class provides a TCP-based server
QTcpSocket Class
The QTcpSocket class provides a TCP socket
二、代码
#ifndef TCPCLIENT_H
#define TCPCLIENT_H
#include <QObject>
#include <QTcpSocket>
#include <QTcpServer>
#include <QRunnable>
class tcpclient : public QObject
{
Q_OBJECT
public:
tcpclient(QObject *parent = nullptr);
private slots:
void connected();
void readyRead();
void error(QAbstractSocket::SocketError socketError);
private:
QTcpSocket* m_pTcpSocket;
};
class ClientRunnable : public QRunnable
{
public:
void run();
};
class tcpserver : public QObject
{
Q_OBJECT
public:
tcpserver(QObject *parent = nullptr);
private slots:
void onNewConnection();
void onReadMessage();
private:
QTcpServer * m_pTcpServer;
QTcpSocket * m_pTcpSocket;
};
#endif // TCPCLIENT_H
#include "tcpclient.h"
#include <QTimer>
#include <QDataStream>
#include <QTextCodec>
tcpclient::tcpclient(QObject *parent):
QObject(parent)
{
//1. 创建TCP套接字对象
m_pTcpSocket = new QTcpSocket(this);
//2. 已连接、数据可读、失败信号连接
connect(m_pTcpSocket, &QTcpSocket::connected, this, &tcpclient::connected);
connect(m_pTcpSocket, &QIODevice::readyRead, this, &tcpclient::readyRead);
typedef void (QAbstractSocket::*QAbstractSocketErrorSignal)(QAbstractSocket::SocketError);
connect(m_pTcpSocket, static_cast<QAbstractSocketErrorSignal>(&QTcpSocket::error), this, &tcpclient::error);
//3. 与服务器端建立连接
m_pTcpSocket->connectToHost("127.0.0.1", 8888);
QTimer *ptimer = new QTimer;
connect(ptimer,&QTimer::timeout,this,[=](){
QString txt = "client:你好";
m_pTcpSocket->write(txt.toUtf8());
});
ptimer->start(500);
}
void tcpclient::readyRead()
{
QByteArray ba = m_pTcpSocket->readAll();
qDebug()<<"tcpclient:"<<QString::fromUtf8(ba);
}
void tcpclient::connected()
{
qDebug() << "SimpleTcpSocketClientDemo::connected successfully";
}
void tcpclient::error(QAbstractSocket::SocketError socketError)
{
qDebug() << "tcpclient::error " << socketError;
}
void ClientRunnable::run()
{
tcpclient* pSimpleTcpSocketClient = new tcpclient;
}
tcpserver::tcpserver(QObject *parent):
QObject(parent)
{
m_pTcpServer = new QTcpServer();
m_pTcpServer->listen(QHostAddress::Any,8888);
connect(m_pTcpServer,&QTcpServer::newConnection,this,&tcpserver::onNewConnection);
}
void tcpserver::onNewConnection()
{
m_pTcpSocket = m_pTcpServer->nextPendingConnection();
connect(m_pTcpSocket,&QTcpSocket::readyRead,this,&tcpserver::onReadMessage);
}
void tcpserver::onReadMessage()
{
QByteArray ba = m_pTcpSocket->readAll();
qDebug()<<"tcpserver:"<<QString::fromUtf8(ba);
QString txt = "server:你好";
m_pTcpSocket->write(txt.toUtf8());
}
三、总结
1.客户端创建套接字,连接指定ip和端口,等待套接字触发的readyRead()信号
2.服务端创建QTcpServer监听端口,获取有效链接,等待套接字触发的readyRead()信号
3.注意发送方 接收方编码解码,不然会有乱码显示