Qt教学资料 第10章 Qt 5网络与通信.pptVIP

  • 16
  • 0
  • 约1.67万字
  • 约 58页
  • 2017-05-14 发布于浙江
  • 举报
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)

1亿VIP精品文档

相关文档