QT中的网络编程实例
![QT中的网络编程实例](https://img.360docs.net/img27/0165e65j56j4p3tu19zc-71.webp)
![QT中的网络编程实例](https://img.360docs.net/img27/0165e65j56j4p3tu19zc-02.webp)
QT中的网络编程实例
Qclient.h
/**************************************************************************** ** $Id: /sample/10/qclient.h 2.3.2 edited 2004-10-12 $
**
** Copyright (C) 2004-2005 OURSELEC AS. All rights reserved.
** https://www.360docs.net/doc/2c8487490.html,
** This file is part of an example program for Qt. This example
** program may be used, distributed and modified without limitation. **
*****************************************************************************/
#ifndef QCLIENT_H
#define QCLIENT_H
#include
#include
#include
#include
#include
#include
#include
#include
#include
class QClient : public QWidget
{
Q_OBJECT
public:
QClient(QWidget *parent = 0, const char *name = 0);
private slots:
void closeConnection();
void sendToServer();
void connectToServer();
void socketReadyRead();
void socketConnected();
void socketConnectionClosed();
void socketClosed();
void socketError(int);
private:
QSocket *socket;
QTextView *infoText;
QLineEdit *addrText;
QLineEdit *portText;
QLineEdit *inputText;
};
#endif //QCLIENT_H
Qclient.cpp
/**************************************************************************** ** $Id: /sample/10/qclient.h 2.3.2 edited 2004-10-12 $
**
** Copyright (C) 2004-2005 OURSELEC AS. All rights reserved.
** https://www.360docs.net/doc/2c8487490.html,
** This file is part of an example program for Qt. This example
** program may be used, distributed and modified without limitation. **
*****************************************************************************/ #include "qclient.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
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 *Connect = new QPushButton(tr("Connect"), 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()) );
//create the socket and connect various of its signals
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);
// l->addWidget(Connect, 1);
// l->addWidget(close, 1);
// l->addWidget(quit, 1);
//connect to the server
infoText->append(tr("Tying to connect to the server"));
// socket->connectToHost(host, port);
}
void QClient::closeConnection()
{
socket->close();
if (QSocket::Closing == socket->state()) {
// We have a delayed close
connect(socket, SIGNAL(delayedCloseFinished()),
SLOT(socketClosed()));
} else {
// The socket is closed
socketClosed();
}
}
void QClient::sendToServer()
{
// write to the server
if (QSocket::Connected == socket->state()) {
QTextStream os(socket);
os << inputText->text() << "\n";
inputText->setText("");
} else {
// The socket is unconnected
infoText->append(tr("The server is lost\n"));
}
}
void QClient::connectToServer()
{
// connect to the server
socket->connectToHost(addrText->text(), (portText->text()).toInt()); }
void QClient::socketReadyRead()
{
// read from the server
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("Connection 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"));
}
}
Main.cpp
/**************************************************************************** ** $Id: /sample/10/main.cpp 2.3.2 edited 2004-10-12 $
**
** Copyright (C) 2004-2005 OURSELEC AS. All rights reserved.
** https://www.360docs.net/doc/2c8487490.html,
** This file is part of an example program for Qt. This example
** program may be used, distributed and modified without limitation. **
*****************************************************************************/
#include
#include "qclient.h"
int main( int argc, char **argv )
{
QApplication app( argc, argv );
QClient *client = new QClient( 0 );
app.setMainWidget( client );
client->show();
int result = app.exec();
return result;
}
Server.cpp
/****************************************************************************
** $Id: qt/server.cpp 3.0.5 edited Oct 12 2001 $
**
** Copyright (C) 1992-2000 Trolltech AS. All rights reserved.
**
** This file is part of an example program for Qt. This example
** program may be used, distributed and modified without limitation.
**
*****************************************************************************/
#include
#include
#include
#include
#include
#include
#include
#include
#include
/*
The ClientSocket class provides a socket that is connected with a client.
For every client that connects to the server, the server creates a new
instance of this class.
*/
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;
};
/*
The SimpleServer class handles new connections to the server. For every client that connects, it creates a new ClientSocket -- that instance is now responsible for the communication with that client.
*/
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 newConnection( int socket )
{
(void)new ClientSocket( socket, this );
emit newConnect();
}
signals:
void newConnect();
};
/*
The ServerInfo class provides a small GUI for the server. It also creates the SimpleServer and as a result the server.
*/
class ServerInfo : public QVBox
{
Q_OBJECT
public:
ServerInfo()
{
SimpleServer *server = new SimpleServer( this );
QString itext = QString(
"This is a small 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\n" );
}
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.moc"
以上四个文件,Qclient.h 、Qclient.cpp和Main.cpp 是客户端的程序编译后,在qvfb 上运行,Server.cpp为服务端,编译后,运行在Xwindows上。效果如下图。注:访问端口为:4242