server_example.cpp~

来自「基于qt2.3.7的服务器端网络程序」· CPP~ 代码 · 共 134 行

CPP~
134
字号
#include <qsocket.h>#include <qserversocket.h>#include <qapplication.h>#include <qvbox.h>#include <qtextview.h>#include <qlabel.h>#include <qpushbutton.h>#include <qtextstream.h>#include <stdlib.h>class ClientSocket : public QSocket{	Q_OBJECT public:      ClientSocket(int sock, QObject *parent=0, const char *name=0) : QSocket(parent,name)      {        line=0;     	connect( this, SIGNAL(readyRead()), SLOT(readClient()));     	connect( this, SIGNAL(connectionClosed()), SLOT(connectionClosed()));         	setSocket(sock);      }            ~ClientSocket()       {       }  private slots:      void readClient()      {      	while( canReadLine() )     	{          QTextStream os( this );          os << line << ":" << readLine();          line++;     	}      }      void connectionClosed()      {      	delete this ;      } private:      int line;} ;class SimpleServer : public QServerSocket{      Q_OBJECT public:      SimpleServer(QObject *parent=0) : QServerSocket(4242, 1, parent)      {      	if(!ok())     	{          qWarning("Failed to bind to port 4242");          exit(1);         	}	      }            ~SimpleServer()      {      }            void newConenction( int socket )      {     	(void)new ClientSocket( socket, this );     	emit newConnect();            } signals:      void newConnect();} ;class ServerInfo : public QVBox{      Q_OBJECT public:      ServerInfo()      {	SimpleServer *server = new SimpleServer( this );             QString itext = QString( "This is a simple server example !\n" "Connect with the client now" );                QLabel *lb = new QLabel( itext, this);        lb->setAlignment ( AlignHCenter );        infoText = new QTextView( this );        QPushButton *quit = new QPushButton( "Quit", this );             connect( server, SIGNAL( newConnect() ), SLOT( newConnect() ) );        connect( quit, SIGNAL( clicked() ), qApp, SLOT( quit() ) );            }      ~ServerInfo()      {      }  private slots:      void newConnect()      {      	infoText->append( "New Connection" );      } private:      QTextView *infoText;} ;int main( int argc, char **argv ){      QApplication app( argc,argv );      ServerInfo info;      app.setMainWidget( &info );      info.show();      return app.exec();}#include "Server_example.moc"

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?