I'm trying to access a WebSocket API using the cpprestsdk. The example code I have so far is:
#include <iostream>
#include <cpprest/ws_client.h>
using namespace std;
using namespace web;
using namespace web::websockets::client;
int main() {
websocket_client client;
client.connect("wss://api.poloniex.com").wait();
websocket_outgoing_message out_msg;
out_msg.set_utf8_message("test");
client.send(out_msg).wait();
client.receive().then([](websocket_incoming_message in_msg) {
return in_msg.extract_string();
}).then([](string body) {
cout << body << endl; // test
}).wait();
client.close().wait();
return 0;
}
The page (here) gives the following information:
In order to use the push API, connect to wss://api.poloniex.com and
subscribe to the desired feed [...] In order to receive ticker
updates, subscribe to "ticker".
I can't find out how to subscribe to a channel using this library.
Related
I want to create a dll file that can call some apis and return response (this will be used in a Unity project).
To make thing easier I installed cpprestsdk and followed this simple tutorial and it worked perfectly.
But when I tried changing my code so that I can create a dll, I started getting compilation errors.
Below is my source code -
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
#include "pch.h"
using namespace utility; // Common utilities like string conversions
using namespace web; // Common features like URIs.
using namespace web::http; // Common HTTP functionality
using namespace web::http::client; // HTTP client features
using namespace concurrency::streams; // Asynchronous streams
extern "C" {
void SendRequest() {
auto fileStream = std::make_shared<ostream>();
// Open stream to output file.
pplx::task<void> requestTask = fstream::open_ostream(U("results.html")).then([=](ostream outFile)
{
*fileStream = outFile;
// Create http_client to send the request.
http_client client(U("https://www.bing.com/"));
// Build request URI and start the request.
uri_builder builder(U("/search"));
builder.append_query(U("q"), U("cpprestsdk github"));
return client.request(methods::GET, builder.to_string());
})
// Handle response headers arriving.
.then([=](http_response response)
{
printf("Received response status code:%u\n", response.status_code());
// Write response body into the file.
return response.body().read_to_end(fileStream->streambuf());
})
// Close the file stream.
.then([=](size_t)
{
return fileStream->close();
});
// Wait for all the outstanding I/O to complete and handle any exceptions
try
{
requestTask.wait();
}
catch (const std::exception& e)
{
printf("Error exception:%s\n", e.what());
}
}
}
and my header file -
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
#define SENDREQUEST_API __declspec(dllexport)
extern "C" {
SENDREQUEST_API void SendRequest();
}
and the errors I am getting (truncated) -
1>C:\Users\91805\source\repos\RestAPICalls\RestAPICalls\SendRequest.cpp(5,24): error C2871: 'utility': a namespace with this name does not exist
1>C:\Users\91805\source\repos\RestAPICalls\RestAPICalls\SendRequest.cpp(6,20): error C2871: 'web': a namespace with this name does not exist
1>C:\Users\91805\source\repos\RestAPICalls\RestAPICalls\SendRequest.cpp(7,17): error C2653: 'web': is not a class or namespace name
How can I resolve above errors?
PS: I am using Visual Studio to create dll(s) and able to successfully create a dll that contains no external dependencies (followed from here)
Thanks
If I put all the code snippets in the header file there is no problem.
#pragma once
#include <cpprest/http_client.h>
#include <cpprest/filestream.h>
#include "pch.h"
using namespace utility; // Common utilities like string conversions
using namespace web; // Common features like URIs.
using namespace web::http; // Common HTTP functionality
using namespace web::http::client; // HTTP client features
using namespace concurrency::streams;
//extern "C" {
// SENDREQUEST_API void SendRequest();
//}
#define SENDREQUEST_API __declspec(dllexport)
extern "C" {
SENDREQUEST_API void SendRequest();
}
extern "C" {
void SendRequest() {
auto fileStream = std::make_shared<ostream>();
// Open stream to output file.
pplx::task<void> requestTask = fstream::open_ostream(U("results.html")).then([=](ostream outFile)
{
*fileStream = outFile;
// Create http_client to send the request.
http_client client(U("https://www.bing.com/"));
// Build request URI and start the request.
uri_builder builder(U("/search"));
builder.append_query(U("q"), U("cpprestsdk github"));
return client.request(methods::GET, builder.to_string());
})
// Handle response headers arriving.
.then([=](http_response response)
{
printf("Received response status code:%u\n", response.status_code());
// Write response body into the file.
return response.body().read_to_end(fileStream->streambuf());
})
// Close the file stream.
.then([=](size_t)
{
return fileStream->close();
});
// Wait for all the outstanding I/O to complete and handle any exceptions
try
{
requestTask.wait();
}
catch (const std::exception& e)
{
printf("Error exception:%s\n", e.what());
}
}
}
First of all - I'm a student from Germany, so please excuse my bad english.
At the moment, I'm working on a Project which target is to controll servo Motors on an arduino board by Serial communication through xbee modules.
So now I'm studying the SerialPort but got Problems by using the write().
My plan is to send integer values seperated by a commata through my Serial Port.
Visual Studio Reports an error and says that there is no Argument type that fits.
I really don't know how to handle this problem, because I'm completely new to this whole programming topic.
#include <iostream>
using namespace std;
#using <System.dll>;
using namespace System;
using namespace System::IO::Ports;
using namespace System::Threading;
int main() {
unsigned char values[2] = { 50, 120 };
SerialPort^ mySerialPort = gcnew SerialPort("COM3");
mySerialPort->BaudRate = 9600;
mySerialPort->Open();
while (true) {
mySerialPort->Write(values);
}
}
You can fix it this way:
#include <iostream>
using namespace std;
#using <System.dll>
using namespace System;
using namespace System::IO::Ports;
using namespace System::Threading;
int main() {
// Managed array
cli::array<unsigned char> ^values = { 50, 120 };
SerialPort^ mySerialPort = gcnew SerialPort("COM3");
mySerialPort->BaudRate = 9600;
mySerialPort->Open();
while (true) {
// some work with values goes here...
// We should specify buffer offset and length
mySerialPort->Write(values, 0, values->Length);
}
}
As you noticed, you can also send this data as string:
mySerialPort->WriteLine(String::Format("val1 = {0}; val2 = {1}", values[0], values[1]));
But be warned that mySerialPort->Write() sends raw bytes, and mySerialPort->WriteLine() sends each character as a single byte.
For instance:
cli::array<unsigned char> ^buffer = {123};
// Send one single byte 0x7b
mySerialPort->Write(buffer, 0, buffer->Length);
// Send 3 bytes (0x49, 0x50, 0x51)
mySerialPort->WriteLine(String::Format("{0}", buffer[0]));
I'm wondering how I can do a request to a URL (e.g. download a picture and save it) with POCO in C++?
I got this little code so far
#include <iostream>
#include <string>
#include "multiplication.h"
#include <vector>
#include <HTTPRequest.h>
using std::cout;
using std::cin;
using std::getline;
using namespace Poco;
using namespace Net;
int main() {
HTTPRequest *test = new HTTPRequest("HTTP_GET", "http://www.example.com", "HTTP/1.1");
}
Normally POCO has a great advantage to be very simple even when you know nothing about it and you do not need middle/advance C++ knowledge like you need for boost/asio ( e.g what means enable_share_from_this ... )
Under the poco "installation directory" you find the sample directory, (in my case under poco\poco-1.4.6p4\Net\samples\httpget\src ).
On-line help browsing is also easy and fast (for example browsing classes).
If your understanding of C++ in not enough at the present time go to the university library and borrow Scott Meyers books (Effective C++ and after More effective C++ )
So we adapt the sample code httpget.cpp to the minimal required.
Inside the main:
URI uri("http://pocoproject.org/images/front_banner.jpg");
std::string path(uri.getPathAndQuery());
if (path.empty()) path = "/";
HTTPClientSession session(uri.getHost(), uri.getPort());
HTTPRequest request(HTTPRequest::HTTP_GET, path, HTTPMessage::HTTP_1_1);
HTTPResponse response;
if (!doRequest(session, request, response))
{
std::cerr << "Invalid username or password" << std::endl;
return 1;
}
and the function almost untouched:
bool doRequest(Poco::Net::HTTPClientSession& session,
Poco::Net::HTTPRequest& request,
Poco::Net::HTTPResponse& response)
{
session.sendRequest(request);
std::istream& rs = session.receiveResponse(response);
std::cout << response.getStatus() << " " << response.getReason() << std::endl;
if (response.getStatus() != Poco::Net::HTTPResponse::HTTP_UNAUTHORIZED)
{
std::ofstream ofs("Poco_banner.jpg",std::fstream::binary);
StreamCopier::copyStream(rs, ofs);
return true;
}
else
{
//it went wrong ?
return false;
}
}
I let you arrange things for you and see where the image lands on your disk.
Hope it will help
I have an emulator program written in C++ running on Ubuntu 12.04. There are some settings and options needed for running the program, which are given by the main's arguments. I need to query and control these options via HTTPS from a remote machine/mobile device. I was wondering if someone can help me with that.
There should probably be some libraries for the ease, for example libcurl. I'm not sure how suitable it is for my case, but here is any example of connection setup in libcurl. It's not a must to use any libraries though; just the most efficient/simplest way.
#include <curlpp/cURLpp.hpp>
#include <curlpp/Easy.hpp>
#include <curlpp/Options.hpp>
using namespace curlpp::options;
int main(int, char **)
{
try
{
// That's all that is needed to do cleanup of used resources (RAII style).
curlpp::Cleanup myCleanup;
// Our request to be sent.
curlpp::Easy myRequest;
// Set the URL.
myRequest.setOpt<Url>("http://example.com");
// Send request and get a result.
// By default the result goes to standard output.
myRequest.perform();
}
catch (curlpp::RuntimeError &e)
{
std::cout << e.what() << std::endl;
}
catch (curlpp::LogicError &e)
{
std::cout << e.what() << std::endl;
}
return 0;
}
Please have a look at the following code:
#pragma once
using namespace System::IO::Ports;
using namespace System::Text::RegularExpressions;
using namespace System::Collections::Generic;
ref class SMS
{
public:
SMS(void);
void sendMessage();
private:
System::IO::Ports::SerialPort ^port;
};
And the cpp file
#include "StdAfx.h"
#include "SMS.h"
SMS::SMS(void)
{
//Initialize the Serial Port
port = gcnew System::IO::Ports::SerialPort();
port->PortName = "COM12";
port->BaudRate = 9600;
port->Parity = Parity::None;
port->DataBits = 8;
port->StopBits = StopBits::One;
port->Handshake = Handshake::RequestToSend;
port->DtrEnable = true;
port->RtsEnable = true;
port->NewLine = System::Environment::NewLine;
if(!port->IsOpen)
{
port->Open();
}
//Set message format
port->WriteLine("AT+CMGF=1");
//Turn off echo
port->WriteLine("ATE0");
//Set memory configurations
port->WriteLine("AT+CPMS=\"ME\",\"ME\",\"ME\"");
}
//This method will send the SMS
void SMS::sendMessage()
{
if(!port->IsOpen)
{
port->Open();
}
port->WriteLine("AT+CMGS=\"012121212\"");
port->WriteLine("Test Message From C#");
port->WriteLine(System::Convert::ToString((char)(26)));
port->Close();
}
I am trying to send SMS by accessing the dongle. The port is correct and the dongle also fine because it responded to my friend's code few hours back. What am I doing wrong here? Have I done anything incorrect with C++/CLI ? AT Commands?
try adding "CR" "LF" (Carriage Return and Line Feed characters) after each AT command, some GSM dongles (like SIM900) needem in order to work. I hope this helps
Regards
if for win32,..
prefer using
HFILE OpenFile(
LPCSTR lpFileName, // pointer to filename
LPOFSTRUCT lpReOpenBuff, // pointer to buffer for file information
UINT uStyle // action and attributes
);
with other events,...
if using SMS gateway with modem AT command capability, that's fine for direct read and write to COM port
if U using cell phone, many of this will not work. example nokia 6070, 3100 model group
best test it using hyperterminal.
I used CBuildre6 for
https://sites.google.com/site/xpressdms/rosegarden
cheer.