使用QTcpServer和QTcpSocket创建单客户端接入的tcp服务器比较方便,不需要继承QTcpServer类和QTcpSocket类,但是需要继承QObject类,因为需要使用到信号与槽。。。
在头文件中创建:
QTcpServer类用于监听端口
QTcpSocket类用于 服务端和客户端数据的传递
当QTcpServer监听到一个连接时,会自动触发newConnection()信号。。。
通过newConnection()信号触发自定义槽函数newConnectionSlot()。。。
connect(tcpserver, SIGNAL(newConnection()), this, SLOT(newConnectionSlot()));
当客户端发送数据给服务端时,QTcpSocket自动触发readyRead()信号。
通过readyRead()信号触发自定义槽函数dataReceived();
connect(tcpsocket, SIGNAL(readyRead()),this, SLOT(dataReceived()));
当客户端断开连接时,QTcpSocket自动触发disconnected()信号。
通过disconnected()信号触发槽函数deleteLater()。防止内存泄漏。。
connect(tcpsocket, SIGNAL(disconnected()), tcpsocket, SLOT(deleteLater()));
//头文件
#ifndef TCPSERVER_H
#define TCPSERVER_H
#include
#include
class TcpServer : public QObject //继承QObject类
{
Q_OBJECT //必须添加Q_OBJECT,为了使用信号与槽
public:
TcpServer();
int run(); //服务器启动
private:
QTcpServer *tcpserver;
QTcpSocket *tcpsocket;
protected slots: //槽
void newConnectionSlot();
void dataReceived();
};
cpp文件中,run()函数中开启服务器的监听
在newConnectionSlot()中,通过nextPendingConnection()获取到QtcpSocket对象,通过QtcpSocket获取数据。
而且改代码中只能实现一个QtcpSocket对象传递数据,因为当有新的连接接入时,nextPendingConnection()再次被调用,QtcpSocket对象地址被修改,指向新的QtcpSocket对象。。。
需要实现单服务器多客户端,我们需要给QtcpSocket对象打上标记(标识符),用来区分谁是谁,这样才能区分接收到数据是谁传递过来的(下一章讨论)。。
//CPP文件
#include "tcpserver.h"
#include
#include
TcpServer::TcpServer()
{
tcpserver = new QTcpServer();
connect(tcpserver, SIGNAL(newConnection()), this, SLOT(newConnectionSlot()));
}
int TcpServer::run()
{
if (tcpserver->listen(QHostAddress::Any, 3230))
{
qDebug()<<"[TcpServer]-------------------------------------------------listen sucess"<nextPendingConnection();
qDebug()<<"From ---> "<peerAddress()<<":"<peerPort()<readAll();
if(!buffer.isEmpty())
{
QString command = QString::fromLocal8Bit(buffer);
qDebug()<<"[command]:" << command <