📄 client.cpp
字号:
#include <qsocket.h>#include <qapplication.h>#include <qvbox.h>#include <qhbox.h>#include <qtextview.h>#include <qlineedit.h>#include <qlabel.h>#include <qpushbutton.h>#include <qtextstream.h>class Client : public QVBox{ Q_OBJECTpublic: Client(const QString &host,Q_UINT16 port) { infoText = new QTextView(this); QHBox *hb = new QHBox(this); inputText = new QLineEdit(hb); QPushButton *send = new QPushButton(tr("Send"),hb); QPushButton *close = new QPushButton(tr("Close connection"),this); QPushButton *quit = new QPushButton(tr("Quit"),this); connect(send,SIGNAL(clicked()),SLOT(sendToServer()) ); connect(close,SIGNAL(clicked()),SLOT(closeConnection()) ); connect(quit,SIGNAL(clicked()),qApp,SLOT(quit()) ); socket = new QSocket(this); connect(socket,SIGNAL(connected()),SLOT(socketConnected()) ); connect(socket,SIGNAL(connectionClosed()) ,SLOT(socketConnectionClosed())); connect(socket,SIGNAL(readyRead()),SLOT(socketReadyRead()) ); connect(socket,SIGNAL(error(int)),SLOT(socketError(int)) ); infoText->append(tr("Tring to connect to the server\n")); socket->connectToHost(host,port); } ~Client() { }private slots: void closeConnection() { socket->close(); if(socket->state() == QSocket::Closing) { connect(socket,SIGNAL(delayedCloseFinished()),SLOT(socketClosed()) ); } else { socketClosed(); } } void sendToServer() { QTextStream os(socket); os << inputText->text() << "\n"; inputText->setText(""); } void socketReadyRead() { while(socket->canReadLine() ) { infoText->append(socket->readLine() ); } } void socketConnected() { infoText->append(tr("Connected to server\n") ); } void socketConnectionClosed() { infoText->append(tr("Connection closed by the server\n") ); } void socketClosed() { infoText->append(tr("Connection closed\n") ); } void socketError(int e) { infoText->append(tr("Error number %l occurred\n").arg(e) ); }private: QSocket *socket; QTextView *infoText; QLineEdit *inputText;};int main( int argc,char** argv){ QApplication app(argc,argv); Client client(argc<2 ?"localhost":argv[1],4242); app.setMainWidget(&client); client.show(); return app.exec();}#include "client.moc"
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -