Error while consuming REST service in VC++ - rest

I have used the below code to use as an example to consume the REST services in VC++. I am getting an error stating "A Connection with the Server Could Not be Established". IIs version of my system is IIS 6.0. Please let me know what could be the problem. Thanks in advance.
#include "stdafx.h"
#include "http_client.h"
#include "filestream.h"
#include "iostream"
#include "sstream"
#include "conio.h"
#include "Windows.h"
using namespace utility;
using namespace web;
using namespace web::http;
using namespace web::http::client;
using namespace concurrency::streams;
int _tmain(int argc, _TCHAR* argv[])
{
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("http://www.bing.com/"));
uri_builder builder(U("/search"));
builder.append_query(U("q"), U("Casablanca CodePlex"));
return client.request(methods::GET, builder.to_string());
// Build request URI and start the request.
})
// 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());
}
Sleep(5000);
return 0;
}

Related

Boost Beast async rest client : async_resolve - resolve: Host not found (authoritative)

I have the async boost rest client code. I am able to compile and run this code using Cygwin on Windows.
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
namespace http = boost::beast::http; // from <boost/beast/http.hpp>
void
fail(boost::system::error_code ec, char const* what)
{
std::cerr << what << ": " << ec.message() << "\n";
}
// Performs an HTTP GET and prints the response
class session : public std::enable_shared_from_this<session>
{
tcp::resolver resolver_;
tcp::socket socket_;
boost::beast::flat_buffer buffer_; // (Must persist between reads)
http::request<http::empty_body> req_;
http::response<http::string_body> res_;
public:
// Resolver and socket require an io_context
explicit
session(boost::asio::io_context& ioc)
: resolver_(ioc)
, socket_(ioc)
{
}
// Start the asynchronous operation
void
run(char const* host, char const* port, char const* target, int version)
{
// Set up an HTTP GET request message
req_.version(version);
req_.method(http::verb::get);
req_.target(target);
req_.set(http::field::host, host);
req_.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
// Look up the domain name
resolver_.async_resolve(host, port,std::bind( &session::on_resolve, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
}
void
on_resolve( boost::system::error_code ec, tcp::resolver::results_type results)
{
if(ec) {
return fail(ec, "resolve");
}
// Make the connection on the IP address we get from a lookup
boost::asio::async_connect(socket_,results.begin(),results.end(),std::bind(&session::on_connect,shared_from_this(), std::placeholders::_1));
}
void
on_connect(boost::system::error_code ec)
{
if(ec) {
return fail(ec, "connect");
}
// Send the HTTP request to the remote host
http::async_write(socket_, req_,std::bind(&session::on_write, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
}
void
on_write( boost::system::error_code ec, std::size_t bytes_transferred)
{
boost::ignore_unused(bytes_transferred);
if(ec) {
return fail(ec, "write");
}
// Receive the HTTP response
http::async_read(socket_, buffer_, res_, std::bind( &session::on_read, shared_from_this(), std::placeholders::_1, std::placeholders::_2));
}
void
on_read(boost::system::error_code ec, std::size_t bytes_transferred)
{
boost::ignore_unused(bytes_transferred);
if(ec) {
return fail(ec, "read");
}
// Write the message to standard out
std::cout << res_ << std::endl;
// Gracefully close the socket
socket_.shutdown(tcp::socket::shutdown_both, ec);
// not_connected happens sometimes so don't bother reporting it.
if(ec && ec != boost::system::errc::not_connected) {
return fail(ec, "shutdown");
}
// If we get here then the connection is closed gracefully
}
};
int main(int argc, char** argv)
{
// Check command line arguments.
if(argc != 4 && argc != 5)
{
std::cerr <<
"Usage: http-client-async <host> <port> <target> [<HTTP version: 1.0 or 1.1(default)>]\n" <<
"Example:\n" <<
" http-client-async www.example.com 80 /\n" <<
" http-client-async www.example.com 80 / 1.0\n";
return EXIT_FAILURE;
}
auto const host = argv[1];
auto const port = argv[2];
auto const target = argv[3];
int version = argc == 5 && !std::strcmp("1.0", argv[4]) ? 10 : 11;
// The io_context is required for all I/O
boost::asio::io_context ioc;
// Launch the asynchronous operation
std::make_shared<session>(ioc)->run(host, port, target, version);
// Run the I/O service. The call will return when
// the get operation is complete.
ioc.run();
return EXIT_SUCCESS;
}
I have a python REST Server that runs waiting for requests from this client.
#!flask/bin/python
from flask import Flask, jsonify
app = Flask(__name__)
tasks = [
{
'id': 1,
'title': u'Buy groceries',
'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
'done': False
},
{
'id': 2,
'title': u'Learn Python',
'description': u'Need to find a good Python tutorial on the web',
'done': False
}
]
#app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
if __name__ == '__main__':
app.run(host='0.0.0.0',debug=True)
I am able to run this server. The output is shown below.
* Serving Flask app 'RESTServer' (lazy loading)
* Environment: production
WARNING: This is a development server. Do not use it in a production deployme
nt.
Use a production WSGI server instead.
* Debug mode: on
* Restarting with stat
* Debugger is active!
* Debugger PIN: 409-562-797
* Running on all addresses.
WARNING: This is a development server. Do not use it in a production deployme
nt.
* Running on http://192.168.1.104:5000/ (Press CTRL+C to quit)
However when I run the REST Client, as below
rest_client.exe http://192.168.1.104 5000 /todo/api/v1.0/tasks
I get the following error
resolve: Host not found (authoritative)
The program expects separate arguments. It even gives you usage instructions:
Usage: http-client-async <host> <port> <target> [<HTTP version: 1.0 or 1.1(default)>]
Example:
http-client-async www.example.com 80 /
http-client-async www.example.com 80 / 1.0
So it looks like you AT LEAST want to remove http://

Problem executing code (C/Mongo C driver) on different installation than where first compiled

I have a program compiled and running on Ubuntu server 16.04, in C using Mongo C driver. This works without a problem. If I move this executable to a new installation, I get an error when executing;
testuser#usrv1604:~/bin$ ./error-example
./error-example: symbol lookup error: ./error-example: undefined symbol: mongoc_uri_new_with_error
Always the same error message.
Please see simplified code example below:
#include <stdio.h>
#include <strings.h>
#include <mongoc.h>
int
main (int argc, char *argv[])
{
const char *uri_string = "mongodb://localhost:27017";
mongoc_uri_t *uri;
mongoc_client_t *client;
mongoc_database_t *database;
mongoc_collection_t *collection;
bson_t *command, reply, *insert;
bson_t *b;
bson_error_t error;
mongoc_init ();
uri = mongoc_uri_new_with_error (uri_string, &error);
if (!uri) {
fprintf (stderr,
"failed to parse URI: %s\n"
"error message: %s\n",
uri_string,
error.message);
return EXIT_FAILURE;
}
client = mongoc_client_new_from_uri (uri);
if (!client) {
fprintf(stderr, "mongoc_client_new_from_uri() failed \n");
return EXIT_FAILURE;
}
mongoc_client_set_appname (client, "log-lme");
database = mongoc_client_get_database (client, "sds");
collection = mongoc_client_get_collection (client, "sds", "test");
//
// update db
//
// clean up
mongoc_collection_destroy (collection);
mongoc_database_destroy (database);
mongoc_uri_destroy (uri);
mongoc_client_destroy (client);
mongoc_cleanup ();
return EXIT_SUCCESS;
}
Please check the mongoc driver version installed on the target system. You must have version 1.8 or later to use this API: http://mongoc.org/libmongoc/1.8.0/mongoc_uri_new_with_error.html

GTK3 - Catch error when GdkDisplay is unavailable

Given the following code:
#include <gtk/gtk.h>
int main(int argc, char *argv[])
{
gtk_init(&argc, &argv);
GdkDisplay *display = gdk_display_open(":2");
gtk_main();
return(0);
}
How can you catch the error, when the X server for display :2 is no longer running?
The exact error is:
Fatal IO error 11 (Resource temporarily unavailable) on X server :2.

WINSOCK error 10022 on listen when include thread

I am implementing a simple multithreaded FTP client server where I am facing a problem which is strange for me( as I am no master in C++ and threads).
The code I have written works normally until I #include <thread>.
Once I include the thread class the program fails on listen and gives a 10022 error. (I haven't done anything related to threads yet, only import).
Below is the code. The method is called from main().
#include <winsock2.h>
#include <ws2tcpip.h>
#include <process.h>
#include <winsock.h>
#include <iostream>
#include <windows.h>
#include <fstream>
#include <string>
#include <stdio.h>
#include <time.h>
#include <thread>
using namespace std;
void initializeSockets()
{
try{
logEvents("SERVER", "Initializing the server");
WSADATA wsadata;
if (WSAStartup(0x0202,&wsadata)!=0){
cout<<"Error in starting WSAStartup()\n";
logEvents("SERVER", "Error in starting WSAStartup()");
}else{
logEvents("SERVER", "WSAStartup was suuccessful");
}
gethostname(localhost,20);
cout<<"hostname: "<<localhost<< endl;
if((hp=gethostbyname(localhost)) == NULL) {
cout << "gethostbyname() cannot get local host info?"
<< WSAGetLastError() << endl;
logEvents("SERVER", "Cannot get local host info. Exiting....");
exit(1);
}
//Create the server socket
if((serverSocket = socket(AF_INET,SOCK_STREAM,0))==INVALID_SOCKET)
throw "can't initialize socket";
//Fill-in Server Port and Address info.
serverSocketAddr.sin_family = AF_INET;
serverSocketAddr.sin_port = htons(port);
serverSocketAddr.sin_addr.s_addr = htonl(INADDR_ANY);
//Bind the server port
if (bind(serverSocket,(LPSOCKADDR)&serverSocketAddr,sizeof(serverSocketAddr)) == SOCKET_ERROR)
throw "can't bind the socket";
cout << "Bind was successful" << endl;
logEvents("SERVER", "Socket bound successfully.");
if(listen(serverSocket,10) == SOCKET_ERROR)
throw "couldn't set up listen on socket";
else
cout << "Listen was successful" << endl;
logEvents("SERVER", "Socket now listening...");
//Connection request accepted.
acceptUserConnections();
}
catch(char* desc)
{
cerr<<str<<WSAGetLastError()<<endl;
logEvents("SERVER", desc);
}
logEvents("SERVER", "Closing client socket...");
closesocket(clientSocket);
logEvents("SERVER", "Closed. \n Closing server socket...");
closesocket(serverSocket);
logEvents("SERVER", "Closed. Performing cleanup...");
WSACleanup();
}
int main(void){
initializeSockets();
return 0;
}
I have read the thread Winsock Error 10022 on Listen but I don't think that this has solution to my problem.
Error 10022 is WSAEINVAL. The documentation for listen() clearly states:
WSAEINVAL
The socket has not been bound with bind.
The reason your code stops working when you add #include <thread> is because your call to bind() is being altered to no longer call WinSock's bind() function, but to instead call the STL's std::bind() function. Your using namespace std statement is masking that issue (this is one of many reasons why using namespace std is such a bad practice - teach yourself to stop using that!).
So you need to either:
get rid of using namespace std.
qualify bind() with the global namespace so it calls WinSock's function:
if (::bind(...) == SOCKET_ERROR)

how to connect client immediately one after the other in tcp socket api program

server.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<poll.h>
#include<unistd.h>
#include<arpa/inet.h>
int main()
{
struct pollfd fdarray[5];
int sfd,port,nsfd,n,clen,ret,i;
char str[100];
struct sockaddr_in sadd,cadd;
memset(str,0,sizeof(str));
sfd=socket(AF_INET,SOCK_STREAM,0);
if(sfd<0)
{
printf("sorry unable to open the file");
exit(1);
}
memset(&sadd,0,sizeof(sadd));
sadd.sin_port=htons(9796);
sadd.sin_family=AF_INET;
sadd.sin_addr.s_addr=INADDR_ANY;
if(bind(sfd,(struct sockaddr*) &sadd,sizeof(sadd))<0)
{
printf("earror");
exit(0);
}
listen(sfd,5);
clen=sizeof(cadd);
for(i=0;i<5;i++)
{
nsfd=accept(sfd,(struct sockaddr*)&cadd,&clen);
if(nsfd<0)
{
printf("error accepting client");
exit(1);
}
fdarray[i].fd=nsfd;
fdarray[i].events=POLLIN;
fdarray[i].revents=0;
}
while(1)
{
ret=poll(fdarray,5,-1);
for(i=0;i<5;i++)
{
if(fdarray[i].revents==POLLIN)
{
n=read(fdarray[i].fd,str,100);
if(n<0)
printf("arreo");
printf("message is:%s \n",str);
char *buff="message received";
int j;
for( j=0;j<5;j++)
{
if(j!=i)
n=write(fdarray[j].fd,buff,sizeof(buff));
}
}
}
}
return 0;
}
i wrote a program for chat server i.e for example if four client are connected if one of the client send a message then all the other clients should get the message except the sending this process should be done by server i.e client should send to server and server should to all the others now in my code the server waits until all the five clients gets connected what should i do inorder to connect all the clients immediately one after the other not waiting till all are connected
client.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<poll.h>
#include<unistd.h>
int main(int argc,char* argv[])
{
int sfd,i;
char msg[1024];
char blanmsg[1024];
struct sockaddr_in saddr;
memset(&saddr,0,sizeof(saddr));
sfd=socket(AF_INET,SOCK_STREAM,0);
saddr.sin_family=AF_INET;
inet_pton(AF_INET,"127,0.0.1",&saddr.sin_addr);
saddr.sin_port=htons(9796);
connect(sfd,(struct sockaddr*)&saddr,sizeof(saddr));
for(i=0;i<5;i++)
{
fgets(msg,1024,stdin);
send(sfd,msg,strlen(msg),0);
recv(sfd,blanmsg,sizeof(blanmsg),0);
printf("%s",blanmsg);
fflush(stdout);
}
exit(0);
}
If I understand the question correctly: You want to serve already connected clients while some clients are not yet connected.
You can do that by moving client accept()ing into the while(1) loop.
To do that, you must add the server socket to fdarray, and add client sockets to the fdarray when new clients are accepted.
Here is quite similar example: Single thread echo server implemented by using poll()