I have used QTcpSocket and QTcpServer class of qt to establish two way communication. I am able to send data from client to server. But am not getting the response back from server i.e my client.cpp never fires readyRead() signal. I have checked using Wireshark that my data from the server is available in specifed port.
I am posting my client.cpp code( Please help) :
Client::Client(QObject* parent): QObject(parent)
{
socket = new QTcpSocket(this);
connect(socket, SIGNAL(connected()),
this, SLOT(startTransfer()));
connect(socket, SIGNAL(readyRead()),this, SLOT(startRead()));
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(socketError(QAbstractSocket::SocketError)) );
}
Client::~Client()
{
socket->close();
}
void Client::start(QString address, quint16 port)
{
addr.setAddress(address);
socket->connectToHost(addr,port,QTcpSocket::ReadWrite);
}
void Client::startTransfer()
{
printf("Connection established.\n");
char buffer[1024];
forever
{
printf(">> ");
gets(buffer);
int len = strlen(buffer);
buffer[len] = '\n';
buffer[len+1] = '\0';
socket->write(buffer);
socket->flush();
}
}
void Client::startRead()
{
cout<<"inside startRead()<<endl";
while(socket->canReadLine())
{
QByteArray ba = socket->readLine();
if(strcmp(ba.constData(), "!exit\n") == 0)
{
socket->disconnectFromHost();
break;
}
printf(">> %s", ba.constData());
}
}
void Client::socketError(QAbstractSocket::SocketError )
{
qDebug()<<"error" ;
}
Looks like you have forever loop here. This means that your Qt main eventloop never gets the control back after you call startTransfer(). How do you suppose the Qt should run the startRead() code if you block your execution thread with infinite loop?
For Amartel adding the server code:
Server::Server(QObject* parent): QObject(parent)
{
// cout << "Before connect" << endl;
connect(&server, SIGNAL(newConnection()),
this, SLOT(acceptConnection()));
cout << "Listening.." << endl;
server.listen(QHostAddress::Any, 9999);
// cout << "Server started.." << endl;
}
Server::~Server()
{
server.close();
}
void Server::acceptConnection()
{
// cout << "In acceptConnection" << endl;
client = server.nextPendingConnection();
connect(client, SIGNAL(readyRead()),
this, SLOT(startRead()));
}
void Server::startRead()
{
while(client->canReadLine())
{
QByteArray ba = client->readLine();
if(strcmp(ba.constData(), "!exit\n") == 0)
{
client->disconnectFromHost();
break;
}
printf(">> %s", ba.constData());
int result = 0;
bool ack = true;
result = client->write("I Reached");
cout<<result<<endl;
if(result <= 0)
qDebug("Ack NOT sent to client!!!");
else
qDebug("Ack sent to client.");
// client->write("I Reached");
client->flush();
}
}
Related
I'm trying to send some data from QLocalSocket to QLocalSever in a loop. Sever only gets the first data and not receiving subsequent data, but if I introduce 1 mec delay between each call from the client then the server starts to receive everything. Please check out the below Client & Server code.
client.cpp
#include "client.h"
#include "QDataStream"
#include <QTest>
TestClient::TestClient() : m_socket{new QLocalSocket(this)}{
m_socket->connectToServer("TestServer");
if (m_socket->waitForConnected(1000)) {
qDebug("socket Connected!");
}
connect(m_socket, &QLocalSocket::readyRead, this, &TestClient::onNewData);
}
void TestClient::onNewData() {
qCritical() << "data received from server";
}
void TestClient::sendDataToServer() {
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_10);
QString testString = "test data";
out << quint32(testString.size());
out << testString;
m_socket->write(block);
m_socket->flush();
}
void TestClient::startClient() {
for(int i = 0; i < 5; i++) {
//QTest::qWait(1); //works if I uncomment this line
sendDataToServer();
}
}
server.cpp
#include "server.h"
TestServer::TestServer() : m_server{new QLocalServer(this)} {
QLocalServer::removeServer("TestServer");
if (!m_server->listen("TestServer")) {
qCritical() << "couldn't connect to server";
}
connect(m_server, &QLocalServer::newConnection, this, &TestServer::onNewConnection);
}
void TestServer::onNewConnection() {
m_socket = m_server->nextPendingConnection();
connect(m_socket, &QLocalSocket::readyRead, this,
&TestServer::onNewData);
connect(m_socket, &QLocalSocket::disconnected, m_socket,
&QLocalSocket::deleteLater);
}
void TestServer::onNewData() {
QLocalSocket* client = qobject_cast<QLocalSocket*>(sender());
client->readAll();
qCritical() << "data read by server";
}
from the qt doc, it's stated that
readyRead() is not emitted recursively; if you reenter the event loop
or call waitForReadyRead() inside a slot connected to the readyRead()
signal, the signal will not be reemitted (although waitForReadyRead()
may still return true).
so is this my problem? adding timer is the only solution here?
You can compile this test project -> http://www.filedropper.com/testsocket
I'm developing a Qt app which need to read data from weight scale model and can't quite understand how exactly the Bluetooth Low Energy works and how to implement it in Qt.
I have a UC-352BLE weight scale which uses BLE to send data. What I want to achieve is this:
After initial pairing the scale with my Raspberry Pi on which my app is running, when the scale sends data (it does it automatically when you take a measurement), my app receive it. For example I have a blood pressure monitor which uses normal Bluetooth and here it's easy. In my app, I create a QBluetoothServer and call its listen() method. Then when the (already paired) device sends a measurement, it connects with my app automatically, then I create QBluetoothSocket and read the data. But with the scale and it's BLE it seems that you can't do it that way. I tried to follow the Qt documentation on this and right now I just have to manually press the button which connects to the scale when it's sending the data. And every time it connects to the device it discovers it's characteristics and services etc. Don't know if I can do it so the app automatically receives a connection and reads a data when the scale sends a measurement. And even when I try to connects like that sometimes it connects and sometimes don't (I get Unknown error form QLowEnergyController::Error when connecting). Here is what I already have:
Bletest::Bletest(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::Bletest)
{
ui->setupUi(this);
if (localDevice.isValid()) {
localDevice.powerOn();
localDevice.setHostMode(QBluetoothLocalDevice::HostDiscoverable);
connect(&localDevice, &QBluetoothLocalDevice::deviceConnected, this, &Bletest::deviceConnected);
connect(&localDevice, &QBluetoothLocalDevice::deviceDisconnected, this, &Bletest::deviceDisconnected);
connect(&localDevice, &QBluetoothLocalDevice::pairingFinished, this, &Bletest::pairingFinished);
}
discoveryAgent = new QBluetoothDeviceDiscoveryAgent(this);
connect(discoveryAgent, &QBluetoothDeviceDiscoveryAgent::deviceDiscovered, this, &Bletest::addDevice);
connect(discoveryAgent, &QBluetoothDeviceDiscoveryAgent::finished, this, &Bletest::scanFinished);
connect(discoveryAgent, &QBluetoothDeviceDiscoveryAgent::canceled, this, &Bletest::scanFinished);
discoveryAgent->start(QBluetoothDeviceDiscoveryAgent::LowEnergyMethod);
}
Bletest::~Bletest()
{
delete ui;
}
// Local device slots
void Bletest::deviceConnected(const QBluetoothAddress &address)
{
qDebug() << address.toString() << " connected";
}
void Bletest::deviceDisconnected(const QBluetoothAddress &address)
{
qDebug() << address.toString() << " disconnected";
}
void Bletest::pairingFinished(const QBluetoothAddress &address, QBluetoothLocalDevice::Pairing pairing)
{
}
// Agent slots
void Bletest::addDevice(const QBluetoothDeviceInfo &device)
{
if (device.coreConfigurations() & QBluetoothDeviceInfo::LowEnergyCoreConfiguration) {
if (device.name().contains("352")) {
bleDevice = device;
qDebug() << "Found: " + device.name() + "\t" + device.address().toString();
}
}
}
void Bletest::scanFinished()
{
qDebug() << "Devices scan finished";
}
///////////
void Bletest::on_connectButton_clicked()
{
controller = QLowEnergyController::createCentral(bleDevice, this);
connect(controller, &QLowEnergyController::serviceDiscovered, this, &Bletest::serviceDiscovered);
connect(controller, &QLowEnergyController::discoveryFinished, this, &Bletest::serviceScanFinished);
connect(controller, static_cast<void (QLowEnergyController::*)(QLowEnergyController::Error)>(&QLowEnergyController::error),
this, [this](QLowEnergyController::Error error) {
qDebug() << "Cannot connect to device: " + QString::number(error);
});
connect(controller, &QLowEnergyController::connected, this, [this]() {
qDebug() << "Connected to device";
controller->discoverServices();
});
connect(controller, &QLowEnergyController::disconnected, this, [this]() {
qDebug() << "Disconnected";
});
controller->connectToDevice();
}
// Controller slots
void Bletest::serviceDiscovered(const QBluetoothUuid &gatt)
{
qDebug() << "Service discovered: " << gatt.toString();
if (gatt.toString().contains("0000181d-0000-1000-8000-00805f9b34fb")) {
service = controller->createServiceObject(QBluetoothUuid(QBluetoothUuid::WeightScale));
if (service) {
qDebug() << "Found weight scale service";
connect(service, &QLowEnergyService::stateChanged, this, &Bletest::serviceStateChanged);
connect(service, &QLowEnergyService::characteristicChanged, this, &Bletest::updateWeight);
connect(service, &QLowEnergyService::characteristicRead, this, &Bletest::updateWeight);
service->discoverDetails();
}
}
}
void Bletest::serviceScanFinished()
{
qDebug() << "Service scan finished";
}
////////////////////////////
// Service slots
void Bletest::serviceStateChanged(QLowEnergyService::ServiceState newState)
{
if (controller->state() == QLowEnergyController::UnconnectedState)
return;
if (newState == QLowEnergyService::DiscoveringServices) {
qDebug() << "Discovering services state";
} else if (QLowEnergyService::ServiceDiscovered) {
qDebug() << "Service discovered.";
const QLowEnergyCharacteristic weightChar = service->characteristic(QBluetoothUuid(QBluetoothUuid::WeightMeasurement));
if (!weightChar.isValid()) {
qDebug() << "Weight data not found";
return;
}
qDebug() << "Weight data found";
//service->readCharacteristic(weightChar);
desc = weightChar.descriptor(QBluetoothUuid::ClientCharacteristicConfiguration);
if (desc.isValid()) {
qDebug() << "Writing descriptor";
service->writeDescriptor(desc, QByteArray::fromHex("0100"));
}
}
}
void Bletest::updateWeight(const QLowEnergyCharacteristic &c, const QByteArray &value)
{
qDebug() << "Updating weight";
if (c.uuid() != QBluetoothUuid(QBluetoothUuid::WeightMeasurement))
return;
double weight = qFromLittleEndian<qint16>(value.mid(1, 2).data()) * RESOLUTION;
qDebug() << "New weight: " << value.mid(1, 2);
qDebug() << "New weight: " + QString::number(weight, 'f', 2);
}
///////////////////////////
Can someone point me in the right direction with this? Is is even possible with BLE to automatically connects to my app and receive data?
Thanks.
I am using QTCPSockets to talk to a program I've written in Qt for Raspberry Pi. The same software runs on my Mac (or Windows, whatever). The Pi is running a QTCPServer.
I send JSON data to it and most of the time this goes ok.
But sometimes, the Pi is not responding, the data does not seem to arrive. But then, when I send some more data, that data is not being handled, but the previous Json message is! And this stays like this. All the messages are now off by 1. Sending a new messages, triggers the previous one.
It feels a bit connected to this bugreport: https://bugreports.qt.io/browse/QTBUG-58262
But I'm not sure if it is the same.
I've tried waitForBytesWritten and flush and it seemed to work at first, but later I saw the issue again.
I expect that the TCP buffer on the Pi is not being flushed, but I do now know how to make sure that all data is handled right away.
As asked, here is some sourcecode:
This is the client software:
Client::Client() : tcpSocket(new QTcpSocket(this)), in(tcpSocket)
{
connect(tcpSocket, &QIODevice::readyRead, this, &Client::readData);
connect(tcpSocket, &QTcpSocket::connected, this, &Client::connected);
connect(tcpSocket, &QTcpSocket::stateChanged, this, &Client::onConnectionStateChanged);
void (QAbstractSocket:: *sig)(QAbstractSocket::SocketError) = &QAbstractSocket::error;
connect(tcpSocket, sig, this, &Client::error);
}
void Client::connectTo(QString ip, int port) {
this->ip = ip;
this->port = port;
tcpSocket->connectToHost(ip, port);
}
void Client::reconnect() {
connectTo(ip, port);
}
void Client::disconnect()
{
tcpSocket->disconnectFromHost();
}
void Client::connected()
{
qDebug() << TAG << "connected!";
}
void Client::error(QAbstractSocket::SocketError error)
{
qDebug() << TAG << error;
}
void Client::sendData(const QString& data)
{
bool connected = (tcpSocket->state() == QTcpSocket::ConnectedState);
if (!connected) {
qDebug() << TAG << "NOT CONNECTED!";
return;
}
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_7);
out << data;
tcpSocket->write(block);
tcpSocket->flush();
}
void Client::sendData(const QByteArray& data) {
bool connected = (tcpSocket->state() == QTcpSocket::ConnectedState);
if (!connected) {
qDebug() << TAG << " is NOT connected!";
return;
}
tcpSocket->write(data);
tcpSocket->flush();
}
void Client::readData()
{
in.startTransaction();
QString data;
in >> data;
if (!in.commitTransaction())
{
return;
}
emit dataReceived(data);
}
void Client::onConnectionStateChanged(QAbstractSocket::SocketState state)
{
switch (state) {
case QAbstractSocket::UnconnectedState:
connectionState = "Not connected";
break;
case QAbstractSocket::ConnectingState:
connectionState = "connecting";
break;
case QAbstractSocket::ConnectedState:
connectionState = "connected";
break;
default:
connectionState = QString::number(state);
}
qDebug() << TAG << " connecting state: " << state;
emit connectionStateChanged(connectionState);
if (state == QAbstractSocket::UnconnectedState) {
QTimer::singleShot(1000, this, &Client::reconnect);
}
}
and here the server part:
Server::Server()
{
tcpServer = new QTcpServer(this);
connect(tcpServer, &QTcpServer::newConnection, this, &Server::handleConnection);
tcpServer->listen(QHostAddress::Any, 59723);
QString ipAddress;
QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
// use the first non-localhost IPv4 address
for (int i = 0; i < ipAddressesList.size(); ++i) {
if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
ipAddressesList.at(i).toIPv4Address()) {
ipAddress = ipAddressesList.at(i).toString();
break;
}
}
// if we did not find one, use IPv4 localhost
if (ipAddress.isEmpty())
ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
qDebug() << TAG << "ip " << ipAddress << " serverport: " << tcpServer->serverPort();
}
void Server::clientDisconnected()
{
QTcpSocket *client = qobject_cast<QTcpSocket *>(QObject::sender());
int idx = clients.indexOf(client);
if (idx != -1) {
clients.removeAt(idx);
}
qDebug() << TAG << "client disconnected: " << client;
client->deleteLater();
}
void Server::handleConnection()
{
qDebug() << TAG << "incoming!";
QTcpSocket* clientConnection = tcpServer->nextPendingConnection();
connect(clientConnection, &QAbstractSocket::disconnected, this, &Server::clientDisconnected);
connect(clientConnection, &QIODevice::readyRead, this, &Server::readData);
clients.append(clientConnection);
broadcastUpdate(Assets().toJson());
}
void Server::readData()
{
QTcpSocket *client = qobject_cast<QTcpSocket *>(QObject::sender());
QDataStream in(client);
in.startTransaction();
QString data;
in >> data;
if (!in.commitTransaction())
{
return;
}
...
// here I do something with the data. I removed that code as it is
// not necessary for this issue
...
broadcastUpdate(data);
}
void Server::broadcastUpdate(const QString& data)
{
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_5_7);
out << data;
foreach(QTcpSocket* client, clients) {
bool connected = (client->state() == QTcpSocket::ConnectedState);
if (!connected) {
qDebug() << TAG << client << " is NOT connected!";
continue;
}
client->write(block);
}
}
I think the problem is with your void Client::readData(): you have to write it in such a way that you read all available data from the socket inside it (usually it's written with while (socket->bytesAvailable() > 0) { ... } loop).
It is because of the way the readyRead() signal is emitted: the remote peer may send any non-zero number of packets to you, and your socket will emit any non-zero number of readyRead() signals. In your case, it seems that the server sends two messages but they only cause one readyRead() signal to be emitted on the client.
I wanna make a simple Qt app which can perform task like image below:
I have learnt Fortune Server examples and actually I want this app is just like the combination of Fortune Server and Fortune Client.
dialog.cpp
void Dialog::on_btnListen_clicked(bool checked)
{
if(checked)
{
listener = new ServerSock(this);
if(!listener->listen(QHostAddress::LocalHost,ui->boxPort->value()))
{
QMessageBox::critical(this,tr("Error"),tr("Cannot listen: %1").arg(listener->errorString()));
ui->btnListen->setChecked(false);
return;
}
else
{
qDebug() << "Server is listening to port" << listener->serverPort();
ui->btnListen->setText(tr("Listening"));
this->setWindowTitle(tr("Listening and Running"));
}
}
else
{
listener->close();
listener->deleteLater();
ui->tmbListen->setText(tr("Listen again"));
this->setWindowTitle(tr("Taking a rest"));
}
}
serversock.cpp:
#include "serversock.h"
ServerSock::ServerSock(QObject *parent) :
QTcpServer(parent)
{
}
void ServerSock::incomingConnection(int descriptor)
{
thread = new Threading(descriptor,this);
connect(thread,SIGNAL(finished()),thread,SLOT(deleteLater()));
thread->start();
}
threading.cpp:
#include "threading.h"
Threading::Threading(int descriptor, QObject *parent) :
QThread(parent)
{
this->descriptorSocket = descriptor;
}
void Threading::run()
{
qDebug() << "Thread is started...";
socketThread = new QTcpSocket();
if(!socketThread->setSocketDescriptor(this->descriptorSocket))
{
emit error(socketThread->error());
return;
}
connect(socketThread,SIGNAL(readyRead()),this,SLOT(readyToRead()),Qt::DirectConnection);
connect(socketThread,SIGNAL(disconnected()),this,SLOT(unconnected()),Qt::DirectConnection);
qDebug() << descriptorSocket << "Connected";
exec(); //loop
}
void Threading::readyToRead()
{
QByteArray data = socketThread->readAll();
socketOut = new QTcpSocket();
socketOut->connectToHost("192.168.0.1",8080);
if(socketOut->waitForConnected(5000))
{
QByteArray query("GET http:// mysite. com/page HTTP/1.1\r\nHost: anothersite.com\r\r\r\n" + data); //example
socketOut->write(query);
socketOut->write("\r\r\r\n");
socketOut->waitForBytesWritten(1000);
socketOut->waitForReadyRead(3000);
outPut = socketOut->readAll();
if(socketOut->error() != socketOut->UnknownSocketError)
{
qDebug() << socketOut->errorString();
socketOut->disconnectFromHost();
this->quit();
socketThread->abort();
}
else
{
socketOut->close();
}
}
else
{
qDebug() << "Cannot connected";
}
if(!outPut.isNull())
socketThread->write(outPut);
qDebug() << descriptorSocket << " Data in: " << data;
void Threading::unconnected()
{
qDebug() << "Disconnected";
socketThread->abort();
exit(0);
deleteLater();
}
The problem is that I don't know how to return data from remote host to the local client, like the image below:
it sends request, but there is no response. How to accomplish this?
My goal is to transmit *.wav file over LAN network without delay or with minimal one.
Also we read a file on a server machine by parts, 320 bytes both. After this we send packets by UDP and write receiving in jitter-buffer. The size of the jitter-buffer is 10.
What delays should I set on timers for clear sound?
Here is the sender:
void MainWindow::on_start_tx_triggered()
{
timer1 = new QTimer (this);
udpSocketout = new QUdpSocket(this);
qDebug()<<"Start";
for (int i = 0; i < playlist.size(); ++i)
{
inputFile.setFileName(playlist.at(i));
qDebug()<<inputFile.fileName();
if (!inputFile.open(QIODevice::ReadOnly))
{
qDebug()<< "file not found;";
}
}
connect(timer1, SIGNAL(timeout()), this, SLOT(writeDatagrams()));
timer1->start(5);
}
void MainWindow::writeDatagrams()
{
if(!inputFile.atEnd()){
payloadout = inputFile.read(320);
}
qDebug()<<payloadout;
QDataStream out(&datagramout, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_7);
out << qint64(0);
out << payloadout;
out.device()->seek(qint64(0));
out << qint64(datagramout.size() - sizeof(qint64));
qint64 writtenBytes = udpSocketout->writeDatagram(datagramout, remoteHOST, remotePORT);
qDebug() << "Sent " << writtenBytes << " bytes.";
}
Here is the receiver and player:
void MainWindow::on_start_rx_triggered()
{
udpSocketin = new QUdpSocket(this);
udpSocketin->bind(localHOST, localPORT);
connect(udpSocketin, SIGNAL(readyRead()),
this, SLOT(readDatagrams()));
QDataStream out(&datagramout, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_7);
timer2 = new QTimer (this);
connect(timer2, SIGNAL(timeout()), this, SLOT(playbuff()));
timer2->start(50);
audioout = new QAudioOutput(format, this);
}
void MainWindow::readDatagrams()
{
datagramin.resize(udpSocketin->pendingDatagramSize());
qint64 receiveBytes = udpSocketin->readDatagram(datagramin.data(), datagramin.size());
qDebug() << "Receive " << receiveBytes << " bytes.";
QDataStream in(&datagramin, QIODevice::ReadOnly);
in.setVersion(QDataStream::Qt_4_7);
quint64 size = 0;
if(in.device()->size() > sizeof(quint64))
{
in >> size;
}
else
return;
if(in.device()->size() < size)
return;
in >> payloadin;
qDebug() << payloadin.size();
emit jitterbuff();
}
void MainWindow::jitterbuff()
{
if (buff_pos < SIZE_OF_BUF)
{
QDataStream out(&buffered, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_7);
out << payloadin;
buff_pos++;
}
else
buff_pos = 0;
}
void MainWindow::playbuff()
{
qDebug() << "YES!!!";
buffer = new QBuffer(&buffered);
buffer->open(QIODevice::ReadOnly);
audioout->start(buffer);
QEventLoop loop;
QTimer::singleShot(50, &loop, SLOT(quit()));
loop.exec();
buffer->close();
}
This problem was solved. QAdioOutput has two modes; there are "push" and "pull". I give a pointer to a QIODevice, and write data directly to this. Solution:
Reading UDP socket:
void MainWindow::on_start_rx_triggered()
{
udpSocketin = new QUdpSocket(this);
udpSocketin->bind(localPORT);
connect(udpSocketin, SIGNAL(readyRead()), this, SLOT(readDatagrams()));
QDataStream out(&datagramout, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_7);
timer2 = new QTimer (this);
connect(timer2, SIGNAL(timeout()), this, SLOT(playbuff()));
timer2->setInterval(15*9);
audioout = new QAudioOutput(format, this);
input = audioout->start();
}
void MainWindow::readDatagrams()
{
if (udpSocketin->hasPendingDatagrams()){
datagramin.resize(udpSocketin->pendingDatagramSize());
qint64 receiveBytes = udpSocketin->readDatagram(datagramin.data(), datagramin.size());
if (receiveBytes <= 0)
{
msg.warning(this, "File ERROR", "The end!", QMessageBox::Ok);
emit on_stop_rx_triggered();
}
QDataStream in(&datagramin, QIODevice::ReadOnly);
in.setVersion(QDataStream::Qt_4_7);
quint64 size = 0;
if(in.device()->size() > sizeof(quint64))
{
in >> size;
}
else return;
in >> rxfilename;
in >> name;
in >> payloadin;
emit jitterbuff();
}
void MainWindow::jitterbuff()
{
if (buff_pos < SIZE_OF_BUF)
{
buffered.append(payloadin);
buff_pos++;
}
else
{
timer2->start();
buffered.clear();
buff_pos = 0;
}
}
void MainWindow::playbuff()
{
if (!buffered.isEmpty())
{
buffer = new QBuffer(&buffered);
buffer->open(QIODevice::ReadOnly);
input->write(buffered);
buffer->close();
}
}
Writing to UDP socket:
void MainWindow::on_start_tx_triggered()
{
timer1 = new QTimer (this);
udpSocketout = new QUdpSocket(this);
inputFile.setFileName(playlist.at(playIDfile));
if (!inputFile.open(QIODevice::ReadOnly))
{
msg.warning(this, "File ERROR", "File not found!", QMessageBox::Ok);
return;
}
fileinfo = new QFileInfo (inputFile);
txfilename = fileinfo->fileName();
ui->playedFile->setText("Now played: " + txfilename);
connect(timer1, SIGNAL(timeout()), this, SLOT(writeDatagrams()));
timer1->start(15);
}
void MainWindow::writeDatagrams()
{
if(!inputFile.atEnd()){
payloadout = inputFile.read(SIZE_OF_SOUND);
QDataStream out(&datagramout, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_7);
out << qint64(0);
out << txfilename;
out << name;
out << payloadout;
out.device()->seek(qint64(0));
out << qint64(datagramout.size() - sizeof(qint64));
qint64 writtenBytes = udpSocketout->writeDatagram(datagramout, remoteHOST, remotePORT);
}
}
If somebody will have seems problem, I will try to help him/her.