QTcpSever


void QTcpServer::incomingConnection(qintptr socketDescriptor)虚函数,发出 newConnection()信号前,调用此函数.可以修改服务器接收后的行为.因为里面有原始的套接字,可以直接把这个套接字放到线程里面用,只需要把 socketDescriptor参数给与新线程即可

多线程服务器

重写QTcpServer

h

#ifndef MYSEVER_H
#define MYSEVER_H

#include <QTcpServer>

class MySever : public QTcpServer
{
    Q_OBJECT
public:
    MySever(QWidget *parent);

protected:
    virtual void incomingConnection(qintptr socketDescriptor);
};

#endif // MYSEVER_H

cpp

#include "mysever.h"
#include <QMessageBox>
#include "socketthread.h"

MySever::MySever(QWidget *parent)
{

}

void MySever::incomingConnection(qintptr socketDescriptor)
{
	//这里面获得socketDescriptor套接字之后,就可以任意搞事情了.下面我们开了一个线程来处理这个链接的小朋友,
	然后线程就可以run()函数里面搞事情了.
    //新连接可用时,先调用此虚函数,然后在发出newConnection()信号
    QMessageBox::about(0, "提示", "有新连接进入");
    //把套接字socketDescriptor传入线程
    SocketThread *thread = new SocketThread(0, socketDescriptor);
    //开启线程
    thread->start();
}

重写线程

h

#ifndef SOCKETTHREAD_H
#define SOCKETTHREAD_H

#include <QThread>
#include <QTcpSocket>
#include <QWidget>

class MyTcpSocket;

class SocketThread : public QThread
{
public:
    SocketThread(QWidget *parent, qintptr p);
private:
    qintptr ptr;
    MyTcpSocket *socket;

protected:
    virtual void run();

};

#endif // SOCKETTHREAD_H

cpp

#include "socketthread.h"
#include <QDebug>
#include "mytcpsocket.h"
#include <QMessageBox>

SocketThread::SocketThread(QWidget *parent, qintptr p) : QThread(parent)
{
    qDebug() << "QThread构造函数依然在 旧线程";
    this->ptr = p;
}

void SocketThread::run()
{
    qDebug() << "开始线程";
    //线程里面开socket.
    MyTcpSocket *socket = new MyTcpSocket(0, this->ptr);
    socket->waitForBytesWritten();
}

重写socket

h

#ifndef MYTCPSOCKET_H
#define MYTCPSOCKET_H

#include <QTcpSocket>

class MyTcpSocket : public QTcpSocket
{
public:
    MyTcpSocket(QWidget *parent, qintptr ptr);

private slots:
    void on_discon();

public:
    void on_connected();
};

#endif // MYTCPSOCKET_H

#include "mytcpsocket.h"
#include <QByteArray>
#include <QString>
#include <QMessageBox>
#include <QDebug>

MyTcpSocket::MyTcpSocket(QWidget *parent, qintptr ptr) : QTcpSocket(parent)
{
	//需要设置原始的套接字
    this->setSocketDescriptor(ptr);
    //下面就是正常处理
    this->on_connected();
    this->connect(this, SIGNAL(disconnected()), this, SLOT(on_discon()));
}

void MyTcpSocket::on_discon()
{
    qDebug() << "有一个客户端断开了连接";
}

void MyTcpSocket::on_connected()
{
    QByteArray arr;
    QDataStream dts(&arr, QIODevice::WriteOnly);
    dts << QString("这是数据");
    this->write(arr);

    qDebug() << "发送成功!";
}

猜你喜欢

转载自blog.csdn.net/wayrboy/article/details/82979777