用Qt写了个简单的Tcp客户端程序:
工程名client;
1> client.pro中不要忘了加入:
QT += network
2> mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtNetwork/QTcpSocket>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_connectBtn_clicked();
void connectedSlot();
void disconnectedSlot();
void readyReadSlot();
void errorSlot(QAbstractSocket::SocketError);
void on_sendBtn_clicked();
void on_clearBtn_clicked();
private:
Ui::MainWindow *ui;
QTcpSocket *socket_;
bool isConnected_;
};
#endif // MAINWINDOW_H
2> mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
isConnected_(false)
{
ui->setupUi(this);
socket_ = new QTcpSocket(this);
connect(socket_, SIGNAL(connected()), this, SLOT(connectedSlot()));
connect(socket_, SIGNAL(disconnected()), this, SLOT(disconnectedSlot()));
connect(socket_, SIGNAL(readyRead()), this, SLOT(readyReadSlot()));
connect(socket_, SIGNAL(error(QAbstractSocket::SocketError)), this,
SLOT(errorSlot(QAbstractSocket::SocketError)));
}
MainWindow::~MainWindow()
{
delete socket_;
delete ui;
}
void MainWindow::connectedSlot()
{
isConnected_ = true;
}
void MainWindow::disconnectedSlot()
{
isConnected_ = false;
socket_->close();
}
void MainWindow::readyReadSlot()
{
QByteArray message = socket_->readAll();
ui->recvEdit->append(message);
}
void MainWindow::errorSlot(QAbstractSocket::SocketError)
{
QMessageBox::information(this, "show", socket_->errorString());
disconnectedSlot();
}
void MainWindow::on_connectBtn_clicked()
{
socket_->connectToHost(ui->addressEdit->text(), ui->portEdit->text().toInt());
}
void MainWindow::on_sendBtn_clicked()
{
if (isConnected_) {
QString str = ui->sendEdit->text();
socket_->write(str.toLatin1().data(), str.length());
} else {
QMessageBox::information(this, "show", "unconnected");
}
}
void MainWindow::on_clearBtn_clicked()
{
ui->recvEdit->clear();
}
3> 上面代码中使用了mainwidnow.ui见名之意应该很容易理解。