.pro 文件
QT += networksever.h
#ifndef SEVER_H#define SEVER_H#include <QObject>#include <QtNetwork/QTcpServer>#include <QtNetwork/QTcpSocket>class sever : public QObject{Q_OBJECTpublic:
explicit sever(QObject *parent = 0);
signals:
public slots:void slotnewconnect();void slotreadmesg();public:
QTcpServer *m_pTcpServer;QTcpSocket *m_pTcpSocket;public:
void startsever();void sendmessage();};#endif // SEVER_H
sever.cpp
#include "sever.h"sever::sever(QObject *parent) :QObject(parent){}void sever::startsever(){m_pTcpServer = new QTcpServer();m_pTcpServer->listen(QHostAddress::Any,52000);this->connect(m_pTcpServer,SIGNAL(newConnection()),this,SLOT(slotnewconnect()));qDebug()<<"listening to 52000"<<endl;}void sever::sendmessage(){QString strMesg = "hello client";m_pTcpSocket->write(strMesg.toStdString().c_str(),strlen(strMesg.toStdString().c_str()));
}void sever::slotnewconnect(){m_pTcpSocket = m_pTcpServer->nextPendingConnection();this->connect(m_pTcpSocket,SIGNAL(readyRead()),this,SLOT(slotreadmesg()));sendmessage();
}void sever::slotreadmesg(){QByteArray qba= m_pTcpSocket->readAll();QString ss=QVariant(qba).toString();//get the client idQHostAddress ip = m_pTcpSocket->peerAddress();QString msg = ip.toString()+" : "+ss;qDebug()<<msg<<endl;
}
main.cpp
#include <QtCore/QCoreApplication>#include "sever.h"int main(int argc, char *argv[]){QCoreApplication a(argc, argv);sever s;s.startsever();
return a.exec();}