//connection类
#ifndef CONNECTION_H
#define CONNECTION_H
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
#include <QList>
#include <QMutex>
class Connection:public QObject
{
Q_OBJECT
public:
int m_nSocketID;//-1 indicate the socket is invalid; else is the global id of the connection
int m_nMsgReceived;
int m_nMsgSent;
QTcpSocket* m_pTcpSocket;
public:
Connection(){m_nSocketID = -1;}
~Connection()
{
if (m_pTcpSocket!=NULL)
{
delete m_pTcpSocket;
}
}
public:
void InitializeConnection(QTcpSocket* socket, int id)
{
m_pTcpSocket = socket;
m_pTcpSocket->setParent(this);
m_nMsgReceived = 0;
m_nMsgSent = 0;
m_nSocketID = id;
}
void DeleteConnection()
{
m_nSocketID = -1;
m_pTcpSocket->disconnect();
// delete m_pTcpSocket; 若delete会报错, ?
m_pTcpSocket = NULL;
}
};
#endif
//server.h
#ifndef SERVER_H
#define SERVER_H
#include <QtGui/QMainWindow>
#include <QObject>
#include <QTcpServer>
#include <QTcpSocket>
#include <QHostAddress>
#include <QList>
#include <QMutex>
#include "ui_base.h"
#include "qtheader.h"
#include "Connection.h"
class Server : public QMainWindow
{
Q_OBJECT
public:
Server(QWidget *parent = 0, Qt::WFlags flags = 0);
~Server();
private:
Ui::BaseClass ui;
public://public variables
QTcpServer* m_pTcpServer;
Connection* m_pConnection;
QMutex m_mutexConnection;//mutex to protect the array
int m_nConnected;
int m_nID;
public:
bool InitializeServers();
void ShowStatusMessage(con