go语言和c++通信的例子

boost 写的一个echo server ,收到 go发起的连接之后会把一个结构体的内容发送给go一边,go语言进行解析,直接贴代码

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 will 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::placeholders::error,
          boost::asio::placeholders::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::placeholders::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::placeholders::error,
            boost::asio::placeholders::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::placeholders::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 代码(tcp 客户端):

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()
}


本文来自:CSDN博客

感谢作者:qfsun

查看原文:go语言和c++通信的例子

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。