Send Structure with pointer in socket program
How to pass the pointer structure in client server program using boost library?
server:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
#include <ctime>
#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/array.hpp>
#include <boost/any.hpp>
using boost::asio::ip::tcp;
struct DataIns
{
char *a;
};
int main()
{
try
{
/*DataIns *DataStru=new DataIns();
DataStru->a="l";*/
DataIns DataStru;
DataStru.a="Krish";
boost::asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), 13));
tcp::socket socket(io_service);
acceptor.accept(socket);
boost::array <char,128> buf;
std::string Mfg;
boost::system::error_code error;
int n=0;
size_t len;
do
{
buf.empty();
len = socket.read_some(boost::asio::buffer(buf), error);
Mfg=buf.at(0);
n=atoi(Mfg.c_str());
switch(n)
{
case 1:
buf.empty();
len =boost::asio::read(socket,boost::asio::buffer((char*)(&DataStru),sizeof(DataStru)),error);
std::cout<<DataStru.a<<std::endl;
break;
case 2: socket.close();
}
}while(n!=2);
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
|
Client
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include <boost/any.hpp>
#include <boost/lexical_cast.hpp>
using boost::asio::ip::tcp;
struct DataIns
{
char *a;
};
int main(int argc, char* argv[])
{
/*DataIns *DataStru = new DataIns();
DataStru->a="k";*/
DataIns DataStru;
DataStru.a="Gopal";
try
{
boost::asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query("127.0.0.1", "13");
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::resolver::iterator end;
tcp::socket socket(io_service);
boost::system::error_code error = boost::asio::error::host_not_found;
socket.connect(*endpoint_iterator++, error);
if (error)
throw boost::system::system_error(error);
int n=0;
std::string msgss;
int i=1;
//size_t d;
do{
std::cout<<"Enter the option"<<std::endl;
std::cin>>n;
std::string msg;
msg=boost::lexical_cast<std::string>( n );
boost::asio::write(socket, boost::asio::buffer(msg,msg.length()));
switch(n)
{
case 1: boost::asio::write(socket,boost::asio::buffer((char*)&(DataStru),sizeof(DataStru)),boost::asio::transfer_all(),error);
break;
case 2:
socket.close(); break;
}
}while(n!=2);
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
getchar();
return 0;
}
|
I got the error in server side
1 2
|
len =boost::asio::read(socket,boost::asio::buffer((char*)(&DataStru),sizeof(DataStru)),error);
std::cout<<DataStru.a<<std::endl;
|
The memory address access voilation error. how to pass the pointer structure?
Thanks in advance.
Topic archived. No new replies allowed.