How to download a file in C++\wxWidgets - c++

How may I download a file in C++ with wxWidgets?
Been googling and everything and nothing shows up! Help appreciated!

Use wxHTTP class for that.
wxHTTP Example Code:
#include <wx/sstream.h>
#include <wx/protocol/http.h>
wxHTTP get;
get.SetHeader(_T("Content-type"), _T("text/html; charset=utf-8"));
get.SetTimeout(10); // 10 seconds of timeout instead of 10 minutes ...
while (!get.Connect(_T("www.google.com")))
wxSleep(5);
wxApp::IsMainLoopRunning();
wxInputStream *httpStream = get.GetInputStream(_T("/intl/en/about.html"));
if (get.GetError() == wxPROTO_NOERR)
{
wxString res;
wxStringOutputStream out_stream(&res);
httpStream->Read(out_stream);
wxMessageBox(res);
}
else
{
wxMessageBox(_T("Unable to connect!"));
}
wxDELETE(httpStream);
get.Close();
If you want more flexible solution consider using libcurl.

Depends on where you want to 'download' it from, and how the file server allows files to be downloaded. The server might use FTP, or HTTP, or something more obscure. There is no way to tell from your question which has no useful information in it.
In general, I would not use wxWidgets for this task. wxWidgets is a GUI frmaework, with some extras for various things that may or may not be helpful in your case.

From HTTP as Andrejs suggest, from FTP using wxFTP
wxFTP ftp;
// if you don't use these lines anonymous login will be used
ftp.SetUser("user");
ftp.SetPassword("password");
if ( !ftp.Connect("ftp.wxwindows.org") )
{
wxLogError("Couldn't connect");
return;
}
ftp.ChDir("/pub");
wxInputStream *in = ftp.GetInputStream("wxWidgets-4.2.0.tar.gz");
if ( !in )
{
wxLogError("Coudln't get file");
}
else
{
size_t size = in->GetSize();
char *data = new char[size];
if ( !in->Read(data, size) )
{
wxLogError("Read error");
}
else
{
// file data is in the buffer
...
}
delete [] data;
delete in;
}
http://docs.wxwidgets.org/stable/wx_wxftp.html#wxftp

You did not define what "downloading a file" means to you.
If you want to use HTTP to retrieve some content, you should use an HTTP client library like libcurl and issue the appropriate HTTP GET request.

Related

PJSIP Received Remote Sip Header

Let's asssume we've two phone and Phone1 & Phone2 they're both has custom sip header
[Phone1] ----calling----> [Phone2] (This is onIncomingCallState for Phone2 and it can read header of Phone1)
[Phone1] <----answer---- [Phone2] (This is answer for Phone2 and it send it's header with it's CallOpParam)
[Phone1] <----OnCallState----> [Phone2] (This is on call state for both, Phone2 has Phone1's header, now Phone1 need to get Phone2's header.)
I'm writing the code at the level of PjSua2 with C++, i can see the log, Phone1 has access the value of header and when i sniff also with the wireshark i can see as well. But how can i handle it at the level of pjsua2, is there any call back or something else?
Usually there are callbacks, in the on_call_media_state. Here is some bare minimum:
void SipApp::on_call_media_state(pjsua_call_id call_id)
{
pjsua_call_info info;
pjsua_call_get_info(call_id, &info);
if (info.media_status == PJSUA_CALL_MEDIA_ACTIVE) {
//pjsua_conf_connect(0, info.conf_slot);
pjsua_conf_connect(info.conf_slot, g_recorder->getSlot());
for(int i=0; i < g_players.count(); i++) {
g_players.at(i)->setSrc(info.conf_slot);
}
g_recorder->setSrc(info.conf_slot);
g_recorder->start();
// rtsp setup - start streaming the conf to a remote IP
if(1){
if (p_rtsp->asServer()) {
p_rtsp->setSrc(0);
p_rtsp->start_streaming();
} else {
p_rtsp->setSrc(0);
p_rtsp->start_recording();
}
}
}
}
Taken from repositry https://github.com/heatblazer/asteriks-debugger/blob/master/Sip/sipapp.cpp
So can you provide more info on what exactly you are missing?
Actually, it is already implemented in the pjsua2 level.
virtual void onCallState(OnCallStatePrm &prm){
..
prm.e.body.tsxState.src.rdata.wholeMsg //this is what i want exactly.
..
}

c++ - WebSocketPP multiple clients

I have problem with WebSocketPP Server. I want it to handle multiple clients.
Here is my OnOpen method:
void Server::onOpen(
Server* srv,
WSServer* ws,
websocketpp::connection_hdl& hdl)
{
ServerPlayerTracker con;
con.con = &hdl;
con.protocolVersion = 0;
con.verified = false;
con.playerID = srv->playerCount++;
con.roomID = 0;
srv->players.push_back(con);
}
But in disconnection i have problem. I cant find what player with ID disconnected. Here is my OnClose method:
void Server::onClose(
Server* srv,
WSServer* ws,
websocketpp::connection_hdl& hdl)
{
for (int i = 0; i < srv->players.size(); i++)
{
if (srv->players[i].connected)
{
if ((*srv->players[i].con).lock() == hdl.lock())
{
printf("[!] Player disconnected with ID: %d\n",
srv->players[i].playerID);
srv->players.erase(srv->players.begin() + i);
}
}
}
}
In line (*srv->players[i].con).lock() == hdl.lock() it throws exception like
'this was 0xFFFFFFFFFFFFFFF7.' in file 'memory' line 75. I think it's problem with converting weak_ptr to shared_ptr. Is there any way to fix that?
My comments seemed enough to fix the problem (see comments).
For future reference and to indicate that this problem has been answered, I have created this answer.
I'm not 100% sure what is (or is not) working in your current code, since it's quite different from the way the connections are stored and retrieved within the example code (See websocketPP github/documentation example "associative storage").
Using the example, it should be rather easy to set up a multiple client structure, in the way it was intended by the library creator.
For your specific error, I believe you're on the right track about the shared/weak pointer conversion.
Best solution would be to use the list in the way it's used in the example.
Especially interesting is the "con_list" which saves all connections.
It's a typedef of std::map<connection_hdl,connection_data,std::owner_less<conn‌​ection_hdl>> con_list; con_list m_connections; and should enable you to store and retrieve connections (and their session data).

AWS C++ SDK UploadPart times out

I am try to upload a file to Amazon S3 using the AWS C++ SDK.
The call to CreateMultipartUpload returns successfully but the following call to UploadPart times out with the following error:
(Aws::String) m_message = "Unable to parse ExceptionName: RequestTimeout Message: Your socket connection to the server was not read from or written to within the timeout period. Idle connections will be closed."
I don't understand why the initiate call works but not the part upload call. There clearly isn't any network issue.
This is my code:
bool FileUploader::uploadChunk() {
Aws::S3::Model::UploadPartRequest request;
request.SetBucket("video");
request.SetKey(_key);
request.SetUploadId(_file->uploadId);
request.SetPartNumber(_file->chunksUploaded + 1);
long file_pos = _file->chunksUploaded * CHUNK_SIZE;
_input_file.seekg(file_pos, std::ios::beg);
_input_file.read(_file_buf, CHUNK_SIZE);
long n_bytes = _input_file.gcount();
if(n_bytes > 0) {
request.SetContentLength(n_bytes);
char_array_buffer buf2(_file_buf, _file_buf + n_bytes);
std::iostream *chunk_stream = new std::iostream(&buf2);
request.SetBody(std::shared_ptr<std::iostream>(chunk_stream));
Aws::S3::Model::UploadPartOutcome response = _client->UploadPart(request);
if(response.IsSuccess()) {
_file->chunksUploaded++;
_uploader->updateUploadStatus(_file);
}
return response.IsSuccess();
}
else {
return false;
}
}
The problem was my method of obtaining a stream for SetBody. I switched to using the boost library instead of a homegrown approach.
typedef boost::iostreams::basic_array_source<char> Device;
boost::iostreams::stream_buffer<Device> stmbuf(_file_buf, n_bytes);
std::iostream *stm = new std::iostream(&stmbuf);
request.SetBody(std::shared_ptr<Aws::IOStream>(stm));
This works well.
I also needed to keep track of the parts I was uploading for the call to CompleteMultipartUpload as follows:
Aws::S3::Model::CompletedPart part;
part.SetPartNumber(request.GetPartNumber());
part.SetETag(response.GetResult().GetETag());
_uploadedParts.AddParts(part);
Alternatively, you can use the TransferManager interface which will do this for you. It has an IOStream interface. In addition we provide a preallocated buffer implementation for iostream:
https://github.com/aws/aws-sdk-cpp/blob/master/aws-cpp-sdk-core/include/aws/core/utils/stream/PreallocatedStreamBuf.h

C++/IOS Websockets using the Poco Library

I've recently started using the Poco library (which I think is great) and I'm trying to create an Server to connect too using an ios application using socket.io - websocket's. I've managed to use an node js implementation to connect but require a C++ implementation. I've stated by instantiating the websocket within the handleRequest method but unsure to what the next steps are...
Any help would be very much appreciated..
virtual void handleRequest(HTTPServerRequest &req, HTTPServerResponse &resp)
{
char buffer[16384];
WebSocket* ws = new WebSocket(req, resp);
//ws->setKeepAlive(false);
int flags;
if (!ws->poll(500,Poco::Net::Socket::SELECT_READ || Poco::Net::Socket::SELECT_ERROR))
{
cout << ".";
}
else
{
int n = ws->receiveFrame(buffer, sizeof(buffer), flags);
if (n > 0)
{
if ((flags & WebSocket::FRAME_OP_BITMASK) == WebSocket::FRAME_OP_BINARY)
{
// process and send out to all other clients
}
}
}
}
Next steps depend on what you are trying to do. Once connected, you have an open channel that you can use for two-way data exchange between browser and server.
For details, see the WebSocketServer example.

Download a single .txt using QFtp

I've got a problem with QFtp. I wanna download a single .txt file with a single line(8 bytes) from my server, so I've written the following code, but it doesn't work.
The file "actions.txt" were created in the folder1 directory. I can see the size of it pretty well in the client-side. But the file is not being written. I'm getting an empty file.
QFile* actionFile = new QFile("action.txt");
QFtp *ftp = new QFtp(parent);
void Dialog::getActionFile()
{
actionFile->open(QIODevice::WriteOnly);
ftp->connectToHost("mydomain.de");
ftp->login("user", "pw");
ftp->cd("folder1");
ftp->get("action.txt",actionFile);
ftp->close();
actionFile->close();
}
Thanks in advance.
The documentation of several methods of QFtp says:
The function does not block and returns immediately. The command is
scheduled, and its execution is performed asynchronously. The function
returns a unique identifier which is passed by commandStarted() and
commandFinished().
So you need to wait for the appropriate signals to be emitted.
Note that you can also use QNetworkRequest to request the whole ftp URL (I think even with username and password inside the URL) to download the file.
I solved my problem.
I treated one step each time the commandFininshed signal was emitted.
like this:
void MainWindow::ftpCommandFinished(int id, bool error)
{
static bool flag = false;
if(ftp->currentCommand() == QFtp::ConnectToHost)
checkUpdate();
if(ftp->currentCommand() == QFtp::Get)
{
file->close();
if(error)
{
QMessageBox::warning(this, "Erro!", ftp->errorString());
deleteLater();
return;
}
if(!flag)
checkVersion();
else{
delete ftp, file;
ftp = 0; file = 0;
}
flag = true;
}
}
the reason of the flag variable is something else that needs further explanations about the program, so i won't go down that road.
Thanks for you help. It somehow helped me a lot.