2022-02-18 使用grpc进行c++服务器的unixsocket通信

本文详细介绍了如何使用gRPC在C++中通过Unixsocket进行服务器间的通信,包括从git克隆依赖库、配置CMake编译、创建和连接Unixsocket,以及展示服务器和客户端的日志输出和文件检查。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

摘要:

grpc编译安装:

grpc地址:

编译方法:

使用git下载依赖库:

使用cmake编译:

使用grpc完成unixsocket通信:

server端:

client端:

编译方式:

启动服务查看unixsocket:

服务端日志

客户端日志

查看unixsocket文件


摘要:

本文说明如何使用grpc进行c++服务器通过unixsocket进行通信

grpc编译安装:

grpc地址:

Tags · grpc/grpc · GitHub

备份地址:

grpc.tar.gz-互联网文档类资源-优快云下载

编译方法:

使用git下载依赖库:

需要注意, 直接从github上clone下来的代码, 缺少第三方库, 需要执行

git submodule update --init

此命令从git上下载需要的第三方库

使用cmake编译:

进入根目录后, 执行以下命令

mkdir -p ./build
cd ./build

cmake ..

make -j"$(nproc)"
make install

使用grpc完成unixsocket通信:

建立unixsocket位置在 /tmp/unixsocket-grpc

server端:

// Copyright 2021 the gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <iostream>
#include <memory>
#include <string>

#ifdef BAZEL_BUILD
#include "examples/protos/helloworld.grpc.pb.h"
#else
#include "helloworld.grpc.pb.h"
#endif

#include <grpcpp/ext/proto_server_reflection_plugin.h>
#include <grpcpp/grpcpp.h>
#include <grpcpp/health_check_service_interface.h>

using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::Status;
using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;

// Logic and data behind the server's behavior.
class GreeterServiceImpl final : public Greeter::Service {
  Status SayHello(ServerContext* context, const HelloRequest* request,
                  HelloReply* reply) override {
    reply->set_message(request->name());
    std::cout << "Echoing: " << request->name() << std::endl;
    return Status::OK;
  }
};

void RunServer() {
  // std::string server_address("unix-abstract:grpc%00abstract");
  std::string server_address("unix:/tmp/unixsocket-grpc");
  GreeterServiceImpl service;
  grpc::EnableDefaultHealthCheckService(true);
  grpc::reflection::InitProtoReflectionServerBuilderPlugin();
  ServerBuilder builder;
  builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
  builder.RegisterService(&service);
  std::unique_ptr<Server> server(builder.BuildAndStart());
  std::cout << "Server listening on " << server_address << " ... ";
  server->Wait();
}

int main(int argc, char** argv) {
  RunServer();

  return 0;
}

client端:

// Copyright 2021 the gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <iostream>
#include <memory>
#include <string>

#ifdef BAZEL_BUILD
#include "examples/protos/helloworld.grpc.pb.h"
#else
#include "helloworld.grpc.pb.h"
#endif

#include <grpcpp/grpcpp.h>

using grpc::Channel;
using grpc::ClientContext;
using grpc::Status;
using helloworld::Greeter;
using helloworld::HelloReply;
using helloworld::HelloRequest;

class GreeterClient {
 public:
  GreeterClient(std::shared_ptr<Channel> channel)
      : stub_(Greeter::NewStub(channel)) {}

  std::string SayHello(const std::string& user) {
    HelloRequest request;
    request.set_name(user);
    HelloReply reply;
    ClientContext context;
    Status status = stub_->SayHello(&context, request, &reply);
    if (status.ok()) {
      return reply.message();
    }
    std::cout << status.error_code() << ": " << status.error_message()
              << std::endl;
    return "RPC failed";
  }

 private:
  std::unique_ptr<Greeter::Stub> stub_;
};

int main(int argc, char** argv) {
  // std::string target_str("unix-abstract:grpc%00abstract");
  std::string target_str("unix:/tmp/unixsocket-grpc");
  GreeterClient greeter(
      grpc::CreateChannel(target_str, grpc::InsecureChannelCredentials()));
  std::string user("arst");
  std::cout << "Sending '" << user << "' to " << target_str << " ... ";
  std::string reply = greeter.SayHello(user);
  std::cout << "Received: " << reply << std::endl;

  return 0;
}

编译方式:

使用cmake

# Copyright 2018 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# cmake build file for C++ helloworld example.
# Assumes protobuf and gRPC have been installed using cmake.
# See cmake_externalproject/CMakeLists.txt for all-in-one cmake build
# that automatically builds all the dependencies before building helloworld.

cmake_minimum_required(VERSION 3.5.1)

project(HelloWorld C CXX)

include(../cmake/common.cmake)

# Proto file
get_filename_component(hw_proto "../../protos/helloworld.proto" ABSOLUTE)
get_filename_component(hw_proto_path "${hw_proto}" PATH)

# Generated sources
set(hw_proto_srcs "${CMAKE_CURRENT_BINARY_DIR}/helloworld.pb.cc")
set(hw_proto_hdrs "${CMAKE_CURRENT_BINARY_DIR}/helloworld.pb.h")
set(hw_grpc_srcs "${CMAKE_CURRENT_BINARY_DIR}/helloworld.grpc.pb.cc")
set(hw_grpc_hdrs "${CMAKE_CURRENT_BINARY_DIR}/helloworld.grpc.pb.h")
add_custom_command(
      OUTPUT "${hw_proto_srcs}" "${hw_proto_hdrs}" "${hw_grpc_srcs}" "${hw_grpc_hdrs}"
      COMMAND ${_PROTOBUF_PROTOC}
      ARGS --grpc_out "${CMAKE_CURRENT_BINARY_DIR}"
        --cpp_out "${CMAKE_CURRENT_BINARY_DIR}"
        -I "${hw_proto_path}"
        --plugin=protoc-gen-grpc="${_GRPC_CPP_PLUGIN_EXECUTABLE}"
        "${hw_proto}"
      DEPENDS "${hw_proto}")

# Include generated *.pb.h files
include_directories("${CMAKE_CURRENT_BINARY_DIR}")

# hw_grpc_proto
add_library(hw_grpc_proto
  ${hw_grpc_srcs}
  ${hw_grpc_hdrs}
  ${hw_proto_srcs}
  ${hw_proto_hdrs})
target_link_libraries(hw_grpc_proto
  ${_REFLECTION}
  ${_GRPC_GRPCPP}
  ${_PROTOBUF_LIBPROTOBUF})

# Targets greeter_[async_](client|server)
foreach(_target
  greeter_client greeter_server 
  greeter_callback_client greeter_callback_server 
  greeter_async_client greeter_async_client2 greeter_async_server)
  add_executable(${_target} "${_target}.cc")
  target_link_libraries(${_target}
    hw_grpc_proto
    ${_REFLECTION}
    ${_GRPC_GRPCPP}
    ${_PROTOBUF_LIBPROTOBUF})
endforeach()

启动服务查看unixsocket:

服务端日志

root@localhost:~/work/github/grpc/examples/cpp/helloworld/build# ./greeter_server 
Server listening on unix:/tmp/unixsocket-grpc ... Echoing: arst

客户端日志

root@localhost:~/work/github/grpc/examples/cpp/helloworld/build# ./greeter_client 
Sending 'arst' to unix:/tmp/unixsocket-grpc ... Received: arst

查看unixsocket文件

root@localhost:~/work/github/grpc/examples/cpp/helloworld/build# file /tmp/unixsocket-grpc 
/tmp/unixsocket-grpc: socket

### C++ 技术栈的组件、工具和框架 C++ 是一种功能强大且灵活的编程语言,广泛应用于系统软件、游戏开发、实时音视频处理、高性能计算等领域。以下是 C++ 技术栈中常见的组件、工具和框架的详细介绍: #### 1. **核心组件** - **标准库 (STL)**:C++ 提供了丰富的标准模板库 (Standard Template Library),包括容器(如 `vector`、`map`)、算法(如 `sort`、`find`)和迭代器等[^1]。 - **多线程支持**:C++11 引入了多线程支持,通过 `<thread>` 和 `<mutex>` 等头文件实现并发编程[^1]。 - **内存管理**:C++ 提供了手动内存管理机制(如 `new` 和 `delete`),同时也支持智能指针(如 `std::shared_ptr` 和 `std::unique_ptr`)以减少内存泄漏的风险[^1]。 #### 2. **开发工具** - **编译器**: - GCC(GNU Compiler Collection):广泛用于 Linux 和其他类 Unix 系统的开发环境。 - Clang/LLVM:以其快速的编译速度和友好的错误信息著称。 - MSVC(Microsoft Visual C++):适用于 Windows 平台的开发环境。 - **调试工具**: - GDB(GNU Debugger):强大的命令行调试工具,适用于 Linux 环境。 - Visual Studio Debugger:集成在 Microsoft Visual Studio 中,提供图形化界面支持。 - **构建工具**: - CMake:跨平台的构建工具,能够生成 Makefile 或项目文件,简化复杂项目的构建过程。 - Ninja:专为速度优化的构建系统,通常与 CMake 配合使用- **版本控制**: - Git:目前最流行的分布式版本控制系统,支持团队协作开发。 #### 3. **常用框架** - **网络通信框架**: - Boost.Asio:一个异步 I/O 框架,提供了对 TCP、UDP 和 HTTP 的支持,适用于开发高性能网络服务[^1]。 - libevent:轻量级的事件驱动框架,常用于开发高并发服务器- **音视频开发框架**: - WebRTC:基于浏览器的实时音视频通信框架,支持点对点连接和数据通道[^2]。 - FFmpeg:功能强大的多媒体处理库,支持音视频解码、编码、转码、流媒体传输等功能。 - **游戏开发框架**: - Unreal Engine:一款商业化的游戏引擎,支持 C++ 开发。 - Unity(部分支持 C++ 插件开发):虽然主要使用 C#,但可以通过插件扩展支持 C++- **微服务框架**: - gRPC:由 Google 开发的远程过程调用框架,支持多种语言,包括 C++,并使用 Protocol Buffers 作为序列化工具。 - Apache Thrift:类似于 gRPC 的框架,支持跨语言的服务开发。 - **并发与性能优化框架**: - TBB(Threading Building Blocks):英特尔提供的并行计算库,支持任务调度和线程池管理。 - folly:Facebook 开源的 C++ 工具库,包含了许多高性能的数据结构和算法。 #### 4. **配套参考书籍资料推荐** - 《Effective C++》:Scott Meyers 著,深入探讨了 C++ 编程的最佳实践。 -C++ Primer》:Stanley B. Lippman 等著,适合初学者和中级开发者学习 C++ 基础知识。 - 《Modern C++ Design》:Andrei Alexandrescu 著,介绍了基于模板元编程的设计模式。 ```cpp // 示例代码:使用 Boost.Asio 实现简单的 TCP 客户端 #include <boost/asio.hpp> #include <iostream> int main() { try { boost::asio::io_context io_context; boost::asio::ip::tcp::resolver resolver(io_context); boost::asio::ip::tcp::socket socket(io_context); auto endpoints = resolver.resolve("example.com", "80"); boost::asio::connect(socket, endpoints); boost::asio::streambuf request; std::ostream request_stream(&request); request_stream << "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n"; boost::asio::write(socket, request); boost::asio::streambuf response; boost::asio::read_until(socket, response, "\r\n"); std::istream response_stream(&response); std::string http_version; response_stream >> http_version; unsigned int status_code; response_stream >> status_code; std::cout << "HTTP Version: " << http_version << ", Status Code: " << status_code << "\n"; } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

悟世者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值