Example of the Go language and C + + communication

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Boost writes an echo server, receives a connection from the go to send the content of a structure to go side, go language parsing, direct paste code

C++


#include <cstdlib>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/asio.hpp>

Using Boost::asio::ip::tcp;

struct music
{
uint32_t ID;
Char name[128];
Char type[128];
};
struct Music m
{
id:3225,
Name: "My heart would go on",
Type: "Mp3@mp4"
};
Class session
{
Public
Session (boost::asio::io_service& Io_service)
: socket_ (Io_service)
{
}

tcp::socket& socket ()
{
return socket_;
}

void Start ()
{
Socket_.async_read_some (Boost::asio::buffer (Data_, Max_length),
Boost::bind (&session::handle_read, this,
Boost::asio::p Laceholders::error,
Boost::asio::p laceholders::bytes_transferred));
}

Private
void Handle_read (const boost::system::error_code& Error,
size_t bytes_transferred)
{
if (!error)
{
memcpy (data_,&m,sizeof (struct music));
Boost::asio::async_write (socket_,
Boost::asio::buffer (Data_, bytes_transferred+sizeof (m)),
Boost::bind (&session::handle_write, this,
Boost::asio::p laceholders::error));
}
Else
{
Delete this;
}
}

void Handle_write (const boost::system::error_code& error)
{
if (!error)
{
Socket_.async_read_some (Boost::asio::buffer (Data_, Max_length),
Boost::bind (&session::handle_read, this,
Boost::asio::p Laceholders::error,
Boost::asio::p laceholders::bytes_transferred));
}
Else
{
Delete this;
}
}

Tcp::socket socket_;
enum {max_length = 1024};
Char Data_[max_length];
};

Class Server
{
Public
Server (boost::asio::io_service& Io_service, short port)
: Io_service_ (Io_service),
Acceptor_ (Io_service, Tcp::endpoint (TCP::V4 (), port))
{
Start_accept ();
}

Private
void Start_accept ()
{
session* New_session = new session (IO_SERVICE_);
Acceptor_.async_accept (New_session->socket (),
Boost::bind (&server::handle_accept, this, new_session,
Boost::asio::p laceholders::error));
}

void Handle_accept (session* new_session,
Const boost::system::error_code& Error)
{
if (!error)
{
New_session->start ();
}
Else
{
Delete new_session;
}

Start_accept ();
}

boost::asio::io_service& Io_service_;
Tcp::acceptor Acceptor_;
};

int main (int argc, char* argv[])
{
Try
{
if (argc! = 2)
{
Std::cerr << "Usage:async_tcp_echo_server <port>\n";
return 1;
}

Boost::asio::io_service Io_service;

using namespace Std; For Atoi.
Server S (io_service, Atoi (argv[1]));

Io_service.run ();
}
catch (std::exception& e)
{
Std::cerr << "Exception:" << e.what () << "\ n";
}

return 0;
}

Go code (TCP client):

Package Main
Import (
"FMT"
"NET"
"OS"
"Unsafe"
"Encoding/binary"
)
Type Music struct{
Id UInt32
Name []byte
Type []byte
}

Func checkconnection (Conn net. Conn,err error) {
if (Err!=nil) {
Fmt. Printf ("Error%v connecting\n", conn)
Os. Exit (1)
}
Fmt. Printf ("Connected with%v\n", conn)
}
Func Main () {
Args:=os. Args
If Len (args)!=2{
Print ("Usage:", Args[0], "string\n")
Return
}
Data:=make ([]byte,1024)
Conn,err:=net. Dial ("TCP", "127.0.0.1:8032")
Checkconnection (Conn,err)
Read:=true
Conn. Write ([]byte (Args[1]))
For read{
Count,err:=conn. Read (data)
Read= (Err==nil)
var m Music
M.name=make ([]byte,128)
M.type=make ([]byte,128)
Fmt. Println ("sizeof Music", unsafe.) Sizeof (M))
Fmt. Println ("Offset of id,name,type", unsafe. Offsetof (m.id), unsafe. Offsetof (m.name), unsafe. Offsetof (M.type))
Fmt. Println ("Length of id,name,type", unsafe. Sizeof (M.id), Len (M.name), Len (M.type))
Nameindex:=int (unsafe. Sizeof (m.id))
Typeindex:=nameindex+len (M.name)
M=music{uint32 (binary. Littleendian.uint32 (Data[0:nameindex])),
Data[nameindex:typeindex],data[typeindex:count]}
Fmt. Printf ("Server syas:id:%v,name:%s,type:%s\n", UInt32 (M.id), String (M.name), String (M.type))
}
Conn. Close ()
}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.