TcpClient::TcpClient( QObject *parent) : QObject(parent){ qDebug() << "TcpClient::TcpClient()"; socket = new QTcpSocket(); socket->connectToHost(QHostAddress("127.0.0.1"), (quint16)5406);}TcpClient::~TcpClient(){ qDebug() << "TcpClient::~TcpClient()"; socket->disconnectFromHost();}
class TcpServer : public QTcpServer{ Q_OBJECTpublic: TcpServer(QObject *parent = 0); ~TcpServer();protected: void incomingConnection(int socketDescriptor);};
TcpServer::TcpServer( QObject *parent ) : QTcpServer(parent){ qDebug() << "TcpServer::TcpServer()"; listen(QHostAddress::Any, 5406); }TcpServer::~TcpServer(){ qDebug() << "TcpServer::~TcpServer()";}void TcpServer::incomingConnection(int socketDescriptor){ qDebug() << "TcpServer::incomingConnection()"; ServerConnection *conn = new ServerConnection(socketDescriptor, this); connect(conn, SIGNAL(finished()), conn, SLOT(deleteLater())); conn->start();}
class ServerConnection : public QThread{Q_OBJECTpublic: ServerConnection(int socketDescriptor, QObject *parent = 0); ~ServerConnection(); void run(); private: int socketDescriptor; };
ServerConnection::ServerConnection( int socketDescriptor, QObject *parent) : QThread(parent), socketDescriptor(socketDescriptor){ qDebug() << "ServerConnection::ServerConnection()";}ServerConnection::~ServerConnection(){ qDebug() << "ServerConnection::~ServerConnection()";}void ServerConnection::run(){ qDebug() << "ServerConnection::run()"; QTcpSocket tcpSocket; if (!tcpSocket.setSocketDescriptor(socketDescriptor)) { return; } //we're in the new thread! ;) //here we can read or write data tcpSocket.disconnectFromHost(); if (tcpSocket.state() != QAbstractSocket::UnconnectedState ) tcpSocket.waitForDisconnected();}
void ServerConnection::run(){ qDebug() << "ServerConnection::run()"; QTcpSocket tcpSocket; if (!tcpSocket.setSocketDescriptor(socketDescriptor)) { return; } //tcpSocket.disconnectFromHost(); //if (tcpSocket.state() != QAbstractSocket::UnconnectedState ) // tcpSocket.waitForDisconnected();}
void ServerCore::incomingConnection(int socketDescriptor) { UserSession* user = new UserSession; // нить user->moveToThread(user); connect(user,SIGNAL(finished()), //важен порядок user,SIGNAL(signalClose())); connect(user,SIGNAL(finished()), user,SLOT(deleteLater()));
void UserSession::run(){ _client = new nSocket(_nsock,this) //потомок QTcpSocket......//нужные связки сигналов и слотов для обратоткиconnect(this, SIGNAL(signalClose()),_client,SLOT(slotCloseSession()));connect(_client,SIGNAL(disconnected()),this, SLOT(quit()));exec();
void nSocket::slotCloseSession(){ if( state() == QTcpSocket::ConnectedState) close();}