tcpSender (客户端无QTcpServer)
private:
QTcpSocket *tcpClient;
QFile *localFile; //要发送的文件
qint64 totalBytes; //数据总大小
qint64 bytesWritten; //已经发送数据大小
qint64 bytesToWrite; //剩余数据大小
qint64 loadSize; //每次发送数据的大小
QString fileName; //保存文件路径
QByteArray outBlock; //数据缓冲区,即存放每次要发送的数据
private slots:
void send(); //连接服务器
void startTransfer(); //发送文件大小等信息
void updateClientProgress(qint64); //发送数据,更新进度条
void displayError(QAbstractSocket::SocketError); //显示错误
void openFile(); //打开文件
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
loadSize = 4*1024;
totalBytes = 0;
bytesWritten = 0;
bytesToWrite = 0;
tcpClient = new QTcpSocket(this);
connect(tcpClient,SIGNAL(connected()),this,SLOT(startTransfer()));
//当连接服务器成功时,发出connected()信号,我们开始传送文件
connect(tcpClient,SIGNAL(bytesWritten(qint64)),this,SLOT(updateClientProgress(qint64)));
//当有数据发送成功时,我们更新进度条
connect(tcpClient,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(displayError(QAbstractSocket::SocketError)));
ui->sendButton->setEnabled(false);
ui->hostLineEdit->setText("192.168.1.100");
ui->portLineEdit->setText("6666");
}
void Widget::openFile() //打开文件
{
fileName = QFileDialog::getOpenFileName(this);
if(!fileName.isEmpty())
{
ui->sendButton->setEnabled(true);
ui->clientStatusLabel->setText(tr("打开文件 %1 成功!").arg(fileName));
}
}
void Widget::send() //连接到服务器,执行发送
{
ui->sendButton->setEnabled(false);
bytesWritten = 0;
//初始化已发送字节为0
ui->clientStatusLabel->setText(tr("连接中…"));
tcpClient->connectToHost(QHostAddress(ui->hostLineEdit->text()),ui->portLineEdit->text().toInt());//连接
}
void Widget::on_openButton_clicked() //打开按钮
{
openFile();
}
void Widget::on_sendButton_clicked() //发送按钮
{
send();
}