Qt Socket 多线程操作

来源:互联网 发布:矢仓枫子 知乎 编辑:程序博客网 时间:2024/06/03 12:34

Qt 关于Socket 多线程通信

        Python下的多线程,请参考:http://blog.csdn.net/lovelyaiq/article/details/78496814

     最近有个项目需要用到Qt中的socket通信,于是就查阅网上的一些资料和QT API的文档,过程虽然比较艰难,但成果确实~,你懂得,现在就和大家分享它们的用法.

首先Qt关于关于Socket需要使用QTcpServer和QTcpSocket,其中QTcpServer做为服务端,而QTcpSocket则作为客户端.通过查看QTcpServer的API,它可以通过两个信号来监测客户端的连接.incomingConnection和newConnection.本文主要介绍incomingConnection的用法,关于newConnection的用法,可以度娘.

1 incomingConnection,它的定义如下:

void QTcpServer::incomingConnection(qintptr socketDescriptor)

This virtual function is called by QTcpServer when a new connection is available. The socketDescriptor argument is the native socket descriptor for the accepted connection.

The base implementation creates a QTcpSocket, sets the socket descriptor and then stores the QTcpSocket in an internal list of pending connections. Finally newConnection() is emitted.

Reimplement this function to alter the server's behavior when a connection is available.

If this server is using QNetworkProxy then the socketDescriptor may not be usable with native socket functions, and should only be used with QTcpSocket::setSocketDescriptor().

Note: If you want to handle an incoming connection as a new QTcpSocket object in another thread you have to pass the socketDescriptor to the other thread and create the QTcpSocket object there and use its setSocketDescriptor() method.

     通过定义,我们需要重写该函数:

class myserver :public QTcpServer{protected:    virtual void incomingConnection(qintptr socketDescriptor);};
     当有新的建立连接时,我们需要起一个线程.
void myserver::incomingConnection(qintptr socketDescriptor){    qDebug()<<"New Connect is connect"<<socketDescriptor;    socketThread * thread=new socketThread();    thread->write_ptr(socketDescriptor);    thread->start();}

      关于线程的定义如下:

class socketThread :public QThread{public:   //定义自己需要的方法或变量   qintptr ptr;   QTcpSocket * socket;//客户端的定义 void write_ptr(qintptr p){ ptr=p; } protected: virtual void run()}
线程起来之后,则需要在起来的线程中完成相应的初始化:

void socketThread::run(){    socket=new QTcpSocket();    socket->setSocketDescriptor(ptr);//客户端的初始化    if(socket->waitForConnected(10000)){        qDebug()<<"Connect Success";    }    else{        qDebug()<<"Connect Fail";    }    while(true){//完成需要的功能     }}
最后,需要服务器监听IP的端口:
 myserver * server; server=new myserver(); server->listen(QHostAddress::AnyIPv4,6665);
当有新的连接请求时,就会进入到incomingConnection代码中.
     至此,关于Socket的多线程的操作流程完毕.这里面还涉及到线程间的资源共享,这个大家可以度娘,度娘的资源还是比较多的.
     以上是关于一个项目的使用总结,里面有什么不对或有误的地方,请大家指出,我们一起讨论学习.