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

来源:互联网 发布:潮州电视台直播软件 编辑:程序博客网 时间:2024/05/17 17:17

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


0 0