当前位置: 代码迷 >> QT开发 >> Qt udp文件传输有关问题
  详细解决方案

Qt udp文件传输有关问题

热度:99   发布时间:2016-04-25 04:49:57.0
Qt udp文件传输问题
目标如下:
  将一个文件中的内容,通过udp协议写入另一个文件中。我现在遇到的问题是,我只能实现客户端和服务端连通,但不能传输数据。贴一下代码,希望高手解答。(在线等,急)

服务端:
server::server()
{
sendButton = new QPushButton("send",this);  
exitButton = new QPushButton("exit",this);

label = new QLabel("SERVER",this);

QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(label);
layout -> addWidget(sendButton);
  layout -> addWidget(exitButton); //以上为布局
 
udpSocket = new QUdpSocket;
udpSocket ->bind(QHostAddress::LocalHost,8848);

connect(sendButton,SIGNAL(clicked()),this,SLOT(send())); //发送
  connect(exitButton,SIGNAL(clicked()),this,SLOT(close())); //退出
  connect(udpSocket,SIGNAL(readyRead()),this,SLOT(receive()));//接收
};

void server::send() //发送函数
{
QString data;
qDebug()<<"in send_slot()";
QFile file("server.dat");
file.open(QIODevice::ReadOnly);
QDataStream in(&file);
in>>data;
file.close();
udpSocket->writeDatagram(qPrintable(data),sizeof(data),QHostAddress::LocalHost,5566);
}

void server::receive() //接收函数
{
char buf[4096];
qDebug()<<"in receive_slot()";
udpSocket->readDatagram(buf,sizeof(buf),0,0);
QString x(buf);
QFile file("server.dat");
file.open(QIODevice::WriteOnly);
QDataStream out(&file);
out<<x;
file.close();
}
-----------------------------------------------------------------

客户端:
client::client()
{
sendButton = new QPushButton("send",this);
exitButton = new QPushButton("exit",this);

label = new QLabel("CLIENT",this);

QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(label);
layout -> addWidget(sendButton);
  layout -> addWidget(exitButton);

udpSocket = new QUdpSocket;
udpSocket->bind(QHostAddress::LocalHost,5566);

connect(sendButton,SIGNAL(clicked()),this,SLOT(send()));
  connect(exitButton,SIGNAL(clicked()),this,SLOT(close()));
  connect(udpSocket,SIGNAL(readyRead()),this,SLOT(receive()));
};

void client::send()
{
QString data;
qDebug()<<"in send_slot()";
QFile file("client.dat");
file.open(QIODevice::ReadOnly);
QDataStream in(&file);
in>>data;
file.close();

udpSocket->writeDatagram(qPrintable(data),sizeof(data),QHostAddress::LocalHost,8848);
}

void client::receive()
{
char buf[4096];
qDebug()<<"in receive_slot()";
udpSocket->readDatagram(buf,4096,0,0);
QString x(buf);
QFile file("client.dat");
file.open(QIODevice::WriteOnly);
QDataStream out(&file);
out<<x;
file.close();
}

P.S:如果要实现分批传输,又应该怎么改呢。(我知道我很菜)

------解决方案--------------------
UDP传输文件大量丢帧,这个问题如何解决?
  相关解决方案