littlebot
Published on 2025-04-08 / 0 Visits
0

【源码】基于Go语言和gRPC框架的简单聊天服务

项目简介

本项目是基于Go语言和gRPC框架构建的简单聊天服务示例。gRPC 能让客户端应用像调用本地对象方法一样直接调用远程服务端应用的方法,使分布式应用和服务的创建更便捷。项目包含服务端和客户端代码,展示了如何定义 gRPC 服务、编译协议文件、实现基本的远程调用功能,以及如何扩展服务方法。

项目的主要特性和功能

  1. 远程过程调用:客户端可像调用本地方法一样调用服务端的方法,实现高效的远程通信。
  2. 多语言支持:gRPC 支持多种编程语言,本项目使用 Go 语言进行开发。
  3. 服务扩展:可以方便地为服务端添加新的方法,供客户端调用。

安装使用步骤

安装

假设用户已经下载了本项目的源码文件,且系统为 macOS。 1. 安装必要的依赖: bash brew install autoconf automake libtool brew tap grpc/grpc brew install --with-plugins grpc 2. 将编译器插件 protoc-gen-go 所在路径添加到环境变量($GOBIN 默认是 $GOPATH/bin): bash export PATH=$PATH:$GOPATH/bin

运行

  1. 进入示例路径: bash cd $GOPATH/src/google.golang.org/grpc/examples/helloworld
  2. 使用 protoc 编译器将 .proto 文件编译成 .pb.go 文件: bash protoc -I helloworld/ helloworld/helloworld.proto --go_out=plugins=grpc:helloworld
  3. 启动服务端: bash go run greeter_server/main.go
  4. 打开一个新的终端,启动客户端: bash go run greeter_client/main.go 此时,客户端将显示服务端的响应信息。

服务扩展

若要给服务端增加新的方法供客户端调用,可按以下步骤操作: 1. 编辑 helloworld/helloworld.proto 文件,添加新的方法,例如 SayHelloAgain: ```js // The greeting service definition. service Greeter { // Sends a greeting rpc SayHello (HelloRequest) returns (HelloReply) {} // Sends another greeting rpc SayHelloAgain (HelloRequest) returns (HelloReply) {} }

// The request message containing the user's name. message HelloRequest { string name = 1; }

// The response message containing the greetings message HelloReply { string message = 1; } 2. 重新使用 `protoc` 编译器编译 `.proto` 文件:bash protoc -I helloworld/ helloworld/helloworld.proto --go_out=plugins=grpc:helloworld 3. 更新服务端 `greeter_server/main.go` 代码,添加新方法的实现:go func (s server) SayHelloAgain(ctx context.Context, in pb.HelloRequest) (*pb.HelloReply, error) { return &pb.HelloReply{Message: "Hello again " + in.Name}, nil } 4. 更新客户端 `greeter_client/main.go` 代码,调用新方法:go r, err = c.SayHelloAgain(ctx, &pb.HelloRequest{Name: name}) if err != nil { log.Fatalf("could not greet: %v", err) } log.Printf("Greeting: %s", r.Message) 5. 重新编译并运行服务端和客户端代码:bash go run greeter_server/main.go 在新终端中:bash go run greeter_client/main.go ```

下载地址

点击下载 【提取码: 4003】【解压密码: www.makuang.net】