Qt Socket 多线程操作

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的多线程的操作流程完毕.这里面还涉及到线程间的资源共享,这个大家可以度娘,度娘的资源还是比较多的.
     以上是关于一个项目的使用总结,里面有什么不对或有误的地方,请大家指出,我们一起讨论学习.

  • 13
    点赞
  • 53
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值