QT TCP简单使用

服务端cpp

#include "server.h"

#include<QMessageBox>
#include<QDebug>
Server::Server(QObject *parent,int port)
    :QTcpServer(parent)
{
    listen(QHostAddress::Any,port);
}
int Server::getAddClient()
{
    return addClient;
}
void Server::setAddClient(int value)
{
    addClient = value;
}
int Server::getDeleteClient()
{
    return deleteClient;
}
void Server::setDeleteClient(int value)
{
    deleteClient = value;
}
int Server::getClientAllNum()
{
    return clientAllNum;
}
void Server::setClientAllNum(int value)
{
    clientAllNum = value;
}
int Server::clientnum=0;
int Server::clientAllNum=0;
int Server::deleteClient=0;
int Server::addClient=0;
//获取客户端数量
int Server::getClientnum()
{
    return clientnum;
}
//设置客户端数量
void Server::setClientnum(int value)
{
    clientnum = value;
}
//发送信息到客户端
void Server::sendMessageToClient(QString msg)
{
    int listLengh=tcpClientSocketList.count();
    if(clientnum<=listLengh && listLengh!=0)
    {
        QTcpSocket *item = tcpClientSocketList.at(clientnum);
        QByteArray datasend =msg.toLocal8Bit();
        item->write(datasend);
//        std::string msgstd=msg.toStdString();
//        const char *msgtoc=msgstd.c_str();
//        if(item->write(msgtoc,msg.length())!=msg.length())
//        {
//            qDebug()<<"msgupdate1";
//        }
    }
}
//发送信息到所有客户端
void Server::sendMessageToAllClient(QString msg)
{
    for(int i=0;i<tcpClientSocketList.count();i++)
    {
        QTcpSocket *item = tcpClientSocketList.at(i);
        QByteArray datasend =msg.toLocal8Bit();
        item->write(datasend);
//        std::string msgstd=msg.toStdString();
//        const char *msgtoc=msgstd.c_str();
//        int length=msg.length();
//        if(item->write(msgtoc,length)!=length)
//        {
//            qDebug()<<length;qDebug()<<"length1";
//            continue;
//        }
    }
}
//建立连接
void Server::incomingConnection(qintptr socketDescriptor)
{
    TcpClientSocket *tcpClientSocket=new TcpClientSocket(this);
    connect(tcpClientSocket,SIGNAL(updateClients(QString,int)),this,SLOT(updateClients(QString,int)));
    connect(tcpClientSocket,SIGNAL(disconnected(int)),this,SLOT(slotDisconnected(int)));
    tcpClientSocket->setSocketDescriptor(socketDescriptor);
    tcpClientSocketList.append(tcpClientSocket);
}
//更新客户端消息
void Server::updateClients(QString msg,int length)
{
    emit updateServer(msg,length);
}
//断开连接时删除客户端
void Server::slotDisconnected(int descriptor)
{
    for(int i=0;i<tcpClientSocketList.count();i++)
    {
        QTcpSocket *item = tcpClientSocketList.at(i);
        if(item->socketDescriptor()==descriptor)
        {
            tcpClientSocketList.removeAt(i);
            deleteClient=i;
            return;
        }
    }
    return;
}

服务端头文件:


#include <QTcpServer>
#include <QObject>
#include "tcpclientsocket.h"
class Server : public QTcpServer
{
    Q_OBJECT
public:
    Server(QObject *parent=0,int port=0);
    QList<TcpClientSocket*> tcpClientSocketList;
    static int clientnum;//指定接收消息的客户端
    static int clientAllNum;//客户端总数
     static int deleteClient;//将移除的客户端
     static int addClient;//将增加的客户端
    static int getClientnum();
    static void setClientnum(int value);
    void sendMessageToClient(QString msg);//发送信息到指定客户端
    void sendMessageToAllClient(QString msg);//发送信息到所有客户端
    static int getClientAllNum();
    static void setClientAllNum(int value);
    static int getDeleteClient();
    static void setDeleteClient(int value);
    static int getAddClient();
    static void setAddClient(int value);
signals:
    void updateServer(QString,int);
public slots:
    void updateClients(QString,int);
    void slotDisconnected(int);
protected:
    void incomingConnection(qintptr socketDescriptor);
private:
};

调用:

server = new Server(this,port);        //port为自己想设置的端口号
connect(server,SIGNAL(updateServer(QString,int)),this,SLOT(updateServer(QString,int)));
void SeverWindow::updateServer(QString msg, int length)
{
    //处理事件
 }

客户端源文件:

#include "tcpclient.h"

QTcpClient::QTcpClient(QObject *parent) : QObject(parent)
{
    port = 8010;
    serverIP = new QHostAddress;
    tcpSocket = new QTcpSocket(this);
    connect(tcpSocket, SIGNAL(connected()), this, SLOT(slotSendtoServer()));
    connect(tcpSocket, SIGNAL(disconnected()), this, SLOT(slotDisConnected()));
    connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(slotReceivedServer()));
}
/**
*函数功能: 设置连接套接字
* 参数: socket:需要设置的套接字
* 返回值: void
*/
void QTcpClient::setTcpSocket(QTcpSocket *socket)
{
    tcpSocket = socket;
}
/**
 *功能:连接服务器
 * 参数:void
 * 返回值: bool 是否连接成功
*/
bool QTcpClient::connectServer(QString ip)
{
    if(!serverIP->setAddress(ip))
    {
        return false;
    }
    else
    {
        tcpSocket->connectToHost(*serverIP, port);
        return true;
    }
}
/**
 *功能:在服务器中注销客户端
 * 参数:void
 * 返回值: void
*/
void QTcpClient::distoryClient()
{
    tcpSocket->disconnectFromHost();
}
/**
 *函数功能:发送数据给服务器
 * 参数:msg 需发送的信息
 * 返回值:void
*/
void QTcpClient::sendtoServer(QString msg)
{
    QByteArray data = msg.toLocal8Bit();
    tcpSocket->write(data);
}
/**
*函数功能: 获取接收到的消息数据
* 参数: void
* 返回值: QString:接收到的消息数据
*/
QString QTcpClient::getReceivedMessage()
{
    return receivedMessage;
}
/**
*函数功能: 设置需发送的消息数据
* 参数: msg:需发送的消息数据
* 返回值: void
*/
void QTcpClient::setSendMessage(QString msg)
{
    sendMessage = msg;
}
/**
*函数功能: 向服务器发送消息的槽函数
* 参数: void
* 返回值: void
*/
void QTcpClient::slotSendtoServer()
{
    sendtoServer(sendMessage);
}
/**
*函数功能: 未连接服务器时的槽函数
* 参数: void
* 返回值: void
*/
void QTcpClient::slotDisConnected()
{
    //连接状态,以后可能用得到
}
/**
*函数功能: 接收服务器发出信息数据的槽函数
* 参数: void
* 返回值: void
*/
void QTcpClient::slotReceivedServer()
{
    //读取缓冲区数据
    QByteArray buffer = tcpSocket->readAll();
    if(!buffer.isEmpty())
    {
        emit setReceivedMessage(QString::fromLocal8Bit(buffer));
    }
}

客户端头文件:


#ifndef TCPCLIENT_H

#define TCPCLIENT_H
#include <QHostAddress>
#include <QTcpSocket>
#include <QHostInfo>
class QTcpClient : public QObject
{
    Q_OBJECT
public:
    explicit QTcpClient(QObject *parent = 0);
public:
    void setTcpSocket(QTcpSocket *socket);
    bool connectServer(QString ip);
    void distoryClient();
    void sendtoServer(QString msg);
    void setSendMessage(QString msg);
    QString getReceivedMessage();
signals:
    void setReceivedMessage(QString msg);
private slots:
    void slotSendtoServer();
    void slotDisConnected();
    void slotReceivedServer();
private:
    int port;                   //端口号
    QHostAddress *serverIP;     //服务器地址
    QTcpSocket *tcpSocket;      //套接字
    QString sendMessage;        //需发送的数据
    QString receivedMessage;    //接受到的数据
};
#endif // TCPCLIENT_H

调用:

QTcpClient tcpClient = new QTcpClient;

connect(tcpClient, SIGNAL(setReceivedMessage(QString)), this, SLOT(receiveMessage(QString)));

bool IsSecceend tcpClient->connectServer("127.0.0.1");    //连接服务器

void QLanderDialog::receiveMessage(QString msg)

{
    //处理事件

}

上一篇:qt 定时器事件QTimerEvent


下一篇:【QT】event事件使用鼠标位置