📄 qclient.cpp
字号:
#include "qclient.h"#include <qsocket.h>#include <qapplication.h>#include <qvbox.h>#include <qhbox.h>#include <qtextview.h>#include <qlineedit.h>#include <qlabel.h>#include <qlayout.h>#include <qpushbutton.h>#include <qtextstream.h>#include <qpoint.h>QClient::QClient(QWidget *parent, const char *name ):QWidget( parent, name ){ infoText = new QTextView(this); QHBox *hb = new QHBox(this); inputText = new QLineEdit(hb); QHBox *addrBox = new QHBox(this); QLabel *ip = new QLabel("IP:", addrBox, "ip" ); ip->setAlignment(1); addrText = new QLineEdit(addrBox); QLabel *port = new QLabel("PORT:", addrBox, "port" ); port->setAlignment(1); portText = new QLineEdit(addrBox); QHBox *buttonBox = new QHBox(this); QPushButton *send = new QPushButton(tr("Send"), hb); QPushButton *close = new QPushButton(tr("Close connection"), buttonBox); QPushButton *quit = new QPushButton(tr("Quit"), buttonBox); QPushButton *Connect = new QPushButton(tr("Connect"), addrBox); connect(send, SIGNAL(clicked()), SLOT(sendToServer())); connect(close, SIGNAL(clicked()), SLOT(closeConnection())); connect(quit, SIGNAL(clicked()), qApp, SLOT(quit())); connect(Connect, SIGNAL(clicked()), SLOT(connectToServer())); 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))); QVBoxLayout *l = new QVBoxLayout(this); l->addWidget(infoText, 10); l->addWidget(hb, 1); l->addWidget(addrBox, 1); l->addWidget(buttonBox, 1); infoText->append(tr("Tying to connect to the server")); }void QClient::closeConnection(){ socket->close(); if (QSocket::Closing == socket->state()) { connect(socket, SIGNAL(delayedCloseFinshed()), SLOT(socketClosed())); }else{ socketClosed(); }}void QClient::sendToServer(){ if(QSocket::Connection == socket->state()) { QTextStream os(socket); os<< inputText->text()<< "\n"; inputText->setText(""); } else { infoText->append(tr("The server is lost\n"));}}void QClient::connectToServer(){ socket->connectToHost(addrText->text(), (portText->text()).toInt());}void QClient::socketReadyRead(){ while(socket->canReadLine()) { infoText->append(socket->readLine()); }}void QClient::socketConnected(){ infoText->append(tr("Connected to server\n"));}void QClient::socketConnectionClosed(){ infoText->append(tr("Connection closed by the server\n"));}void QClient::socketClosed(){ infoText->append(tr("Connected closed\n"));}void QClient::socketError(int e){ if (e==QSocket::ErrConnectionRefused) { infoText->append(tr("Connection Refused\n"));} else if (e==QSocket::ErrHostNotFound) { infoText->append(tr("Host Not Found\n"));} else if (e==QSocket::ErrSocketRead) { infoText->append(tr("Socket Read Error\n"));}}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -