- 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
- 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
10.3.3 TCP服务器 (3)在源文件“tcpclientsocket.cpp”中,构造函数(TcpClientSocket)的内容如下(它指定了信号与槽的连接关系): #include tcpclientsocket.h TcpClientSocket::TcpClientSocket(QObject *parent) { connect(this,SIGNAL(readyRead()),this,SLOT(dataReceived())); connect(this,SIGNAL(disconnected()),this,SLOT(slotDisconnected())); } 10.3.3 TCP服务器 在源文件“tcpclientsocket.cpp”中,dataReceived()函数的具体代码如下: void TcpClientSocket::dataReceived() { while(bytesAvailable()0) { int length = bytesAvailable(); char buf[1024]; read(buf,length); ? QString msg=buf; emit updateClients(msg,length); } } 在源文件“tcpclientsocket.cpp”中,槽函数slotDisconnected()的具体代码如下: void TcpClientSocket::slotDisconnected() { emit disconnected(this-socketDescriptor()); } 10.3.3 TCP服务器 (4)在工程“TcpS”中添加C++ 类文件“server.h”及“server.cpp”,Server继承自QTcpServer,实现一个TCP协议的服务器。利用QTcpServer,开发者可以监听到指定端口的TCP连接。其具体代码如下: #include QTcpServer #include QObject ? #include tcpclientsocket.h //包含TCP的套接字 ? class Server : public QTcpServer { Q_OBJECT //添加宏(Q_OBJECT)是为了实现信号与槽的通信 public: Server(QObject *parent=0,int port=0); QListTcpClientSocket* tcpClientSocketList; signals: void updateServer(QString,int); public slots: void updateClients(QString,int); void slotDisconnected(int); protected: void incomingConnection(int socketDescriptor); }; 10.3.3 TCP服务器 (5)在源文件“server.cpp”中,构造函数(Server)的具体内容如下: #include server.h ? Server::Server(QObject *parent,int port) :QTcpServer(parent) { listen(QHostAddress::Any,port); } 10.3.3 TCP服务器 在源文件“server.cpp”中,当出现一个新的连接时,QTcpSever触发incomingConnection()函数,参数socketDescriptor指定了连接的Socket描述符,其具体代码如下: void Server::incomingConnection(int socketDescriptor) { TcpClientSocket *tcpClientSocket=new TcpClientSocket(this); connect(tcpClientSocket,SIGNAL(updateClients(QString,int)), this,SLOT(updateClients(QString,int))); connect(tcpClientSocket,SIGNAL(disconnected(int)),this, SLOT(slotDisconnect
文档评论(0)