go語言和c++通訊的例子

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

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


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.