├── .gitignore ├── .golangci.yml ├── LICENSE ├── README.md ├── commonutil ├── codec_empty.go ├── gnet_option.go └── log.go ├── examples ├── tcp_fixed_head │ └── tcp_fixed_head_server.go └── websocket │ └── websocket_server.go ├── go.mod ├── go.sum ├── grpc ├── grpc_temp_client.go ├── grpc_temp_server.go └── protobuf │ ├── hello.pb.go │ ├── hello.proto │ ├── temp.pb.go │ └── temp.proto ├── proto_temp.go ├── tcp_fixed_head ├── config.go ├── handler.go ├── handler_context.go ├── protocal.go └── server.go └── websocket ├── client.go ├── config.go ├── data_handler.go ├── server.go ├── timewheel.go └── upgrader.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | *.swp 8 | *.swn 9 | *.swo 10 | 11 | # Test binary, build with `go test -c` 12 | *.test 13 | 14 | # Output of the go coverage tool, specifically when used with LiteIDE 15 | *.out 16 | -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | linters-settings: 2 | depguard: 3 | list-type: blacklist 4 | packages: 5 | # logging is allowed only by logutils.Log, logrus 6 | # is allowed to use only in logutils package 7 | - github.com/sirupsen/logrus 8 | packages-with-error-message: 9 | - github.com/sirupsen/logrus: "logging is allowed only by logutils.Log" 10 | dupl: 11 | threshold: 100 12 | funlen: 13 | lines: 150 14 | statements: 55 15 | gci: 16 | local-prefixes: github.com/golangci/golangci-lint 17 | goconst: 18 | min-len: 2 19 | min-occurrences: 3 20 | gocritic: 21 | enabled-tags: 22 | - diagnostic 23 | - experimental 24 | - opinionated 25 | - performance 26 | - style 27 | disabled-checks: 28 | - dupImport # https://github.com/go-critic/go-critic/issues/845 29 | - ifElseChain 30 | - octalLiteral 31 | - whyNoLint 32 | - wrapperFunc 33 | - unnamedResult 34 | - commentedOutCode 35 | gocyclo: 36 | min-complexity: 25 37 | stylecheck: 38 | go: "1.16" # https://golangci-lint.run/usage/linters/#stylecheck 39 | checks: ["all", "-ST1022"] 40 | goimports: 41 | local-prefixes: github.com/golangci/golangci-lint 42 | golint: 43 | min-confidence: 0 44 | gomnd: 45 | settings: 46 | mnd: 47 | # don't include the "operation" and "assign" 48 | checks: argument,case,condition,return 49 | govet: 50 | check-shadowing: true 51 | settings: 52 | printf: 53 | funcs: 54 | - (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof 55 | - (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf 56 | - (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf 57 | - (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf 58 | lll: 59 | line-length: 140 60 | maligned: 61 | suggest-new: true 62 | misspell: 63 | locale: US 64 | ignore-words: 65 | - colour 66 | nolintlint: 67 | allow-leading-space: true # don't require machine-readable nolint directives (i.e. with no leading space) 68 | allow-unused: false # report any unused nolint directives 69 | require-explanation: false # don't require an explanation for nolint directives 70 | require-specific: false # don't require nolint directives to be specific about which linter is being skipped 71 | 72 | linters: 73 | # please, do not use `enable-all`: it's deprecated and will be removed soon. 74 | # inverted configuration with `enable-all` and `disable` is not scalable during updates of golangci-lint 75 | disable-all: true 76 | enable: 77 | - bodyclose 78 | - deadcode 79 | - depguard 80 | #- dogsled 81 | #- dupl 82 | - errcheck 83 | - exhaustive 84 | - funlen 85 | - gochecknoinits 86 | - goconst 87 | - gocritic 88 | - gocyclo 89 | - gofmt 90 | - goimports 91 | #- golint 92 | #- gomnd 93 | - goprintffuncname 94 | - govet 95 | - ineffassign 96 | - interfacer 97 | - lll 98 | - misspell 99 | - nakedret 100 | - noctx 101 | - nolintlint 102 | - rowserrcheck 103 | - scopelint 104 | - staticcheck 105 | - structcheck 106 | - stylecheck 107 | - typecheck 108 | - unconvert 109 | - unparam 110 | - unused 111 | - varcheck 112 | - whitespace 113 | - wsl 114 | 115 | # don't enable: 116 | # - asciicheck 117 | # - gochecknoglobals 118 | # - gocognit 119 | # - godot 120 | # - godox 121 | # - goerr113 122 | # - maligned 123 | # - nestif 124 | # - prealloc 125 | # - testpackage 126 | # - wsl 127 | 128 | issues: 129 | # Excluding configuration per-path, per-linter, per-text and per-source 130 | exclude-rules: 131 | - path: _test\.go 132 | linters: 133 | - gomnd 134 | 135 | # https://github.com/go-critic/go-critic/issues/926 136 | - linters: 137 | - gocritic 138 | text: "unnecessaryDefer:" 139 | 140 | run: 141 | skip-dirs: 142 | - test/testdata_etc 143 | - internal/cache 144 | - internal/renameio 145 | - internal/robustio 146 | - service/hwobs/obs 147 | skip-files: 148 | - repository/eventrp/timewheel_handler.go 149 | - gotestinit/gotest_init.go 150 | 151 | # golangci.com configuration 152 | # https://github.com/golangci/golangci/wiki/Configuration 153 | service: 154 | golangci-lint-version: 1.23.x # use the fixed version to not introduce new linters unexpectedly 155 | prepare: 156 | - echo "here I can run custom commands, but no preparation needed for this repo" 157 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 connor 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # server_on_gnet 2 | 基于gnet网络框架编写的各种常见服务端server程序,可以用来学习和快速使用 3 | 4 | 目前支持的协议类型 5 | 6 | ## 固定协议头大小,消息体不定长协议支持 7 | ./examples/tcp_fixed_head/tcp_fixed_head_server.go 中是具体的使用demo, 还包含了具体的测试client, 协议是完整的, 可以直接run起来试试 8 | ``` 9 | port := 8081 10 | tcpServer := tcp_fixed_head.NewTCPFixHeadServer(port) 11 | options := []gnet.Option{ 12 | gnet.WithReusePort(true), 13 | gnet.WithMulticore(multicore), 14 | gnet.WithTCPKeepAlive(time.Second * 90), 15 | } 16 | 17 | err := tcp_fixed_head.Run(tcpServer, fmt.Sprintf("tcp://:%d", port), options...) 18 | 19 | ``` 20 | 21 | ## websocket server 22 | ./examples/websocket/websocket_server.go 中是具体的使用demo 23 | 24 | websocket 协议是基于 https://github.com/gobwas/ws 这个库解析的, 25 | 26 | gnet 如何 使用websocket库的? 核心代码是把 gnet.Conn封装一个 io.ReaderWriter接口出来, 具体代码在./websocket/upgrader.go中实现, gnet v2 connection 已兼容reader writer 27 | 28 | ``` 29 | port := 8081 30 | addr := fmt.Sprintf(":%d", port) 31 | tcpServer := websocket.NewEchoServer(addr) 32 | options := []gnet.Option{ 33 | gnet.WithReusePort(true), 34 | gnet.WithMulticore(true), 35 | } 36 | log.Fatal(gnet.Run(tcpServer, fmt.Sprintf("tcp://:%d", port), options...)) 37 | 38 | ``` 39 | 40 | ## todo 41 | 1. mqtt协议 42 | 2. 连接管理 43 | 3. pb协议 44 | 4. thrift协议 45 | 5. 长连接维持平台 46 | -------------------------------------------------------------------------------- /commonutil/codec_empty.go: -------------------------------------------------------------------------------- 1 | package commonutil 2 | 3 | import ( 4 | "github.com/panjf2000/gnet/v2" 5 | ) 6 | 7 | type CodecEmpty struct{} 8 | 9 | func (ce *CodecEmpty) Encode(c gnet.Conn, buf []byte) ([]byte, error) { 10 | return buf, nil 11 | } 12 | 13 | func (ce *CodecEmpty) Decode(c gnet.Conn) ([]byte, error) { 14 | return nil, nil 15 | } 16 | -------------------------------------------------------------------------------- /commonutil/gnet_option.go: -------------------------------------------------------------------------------- 1 | package commonutil 2 | -------------------------------------------------------------------------------- /commonutil/log.go: -------------------------------------------------------------------------------- 1 | package commonutil 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "fmt" 7 | "time" 8 | ) 9 | 10 | const ( 11 | LevelDebug = "DEBUG" 12 | LevelInfo = "INFO" 13 | LevelWarn = "WARN" 14 | LevelError = "ERROR" 15 | 16 | LogPrefix = "SERVER_ON_GNET" 17 | ) 18 | 19 | type LogData struct { 20 | Prefix string `json:"prefix"` 21 | Time string `json:"time"` 22 | Level string `json:"level"` 23 | Content string `json:"content"` 24 | } 25 | 26 | func (ld *LogData) EncodeToStr() (string, error) { 27 | if ld.Prefix == "" { 28 | ld.Prefix = LogPrefix 29 | } 30 | 31 | if ld.Time == "" { 32 | ld.Time = time.Now().Format("2006-01-02 15:04:05") 33 | } 34 | 35 | resBytes, err := json.Marshal(ld) 36 | 37 | return string(resBytes), err 38 | } 39 | 40 | type Logger interface { 41 | Debugf(ctx context.Context, format string, args ...interface{}) 42 | Infof(ctx context.Context, format string, args ...interface{}) 43 | Warnf(ctx context.Context, format string, args ...interface{}) 44 | Errorf(ctx context.Context, format string, args ...interface{}) 45 | } 46 | 47 | var logger Logger = &DefaultLogger{} 48 | 49 | func SetLogger(newLogger Logger) { 50 | logger = newLogger 51 | } 52 | 53 | func GetLogger() Logger { 54 | return logger 55 | } 56 | 57 | type DefaultLogger struct{} 58 | 59 | func (l *DefaultLogger) Debugf(ctx context.Context, format string, args ...interface{}) { 60 | content := fmt.Sprintf(format, args...) 61 | logStr, _ := (&LogData{Level: LevelDebug, Content: content}).EncodeToStr() 62 | fmt.Println(string(logStr)) 63 | } 64 | 65 | func (l *DefaultLogger) Infof(ctx context.Context, format string, args ...interface{}) { 66 | content := fmt.Sprintf(format, args...) 67 | logStr, _ := (&LogData{Level: LevelInfo, Content: content}).EncodeToStr() 68 | fmt.Println(string(logStr)) 69 | } 70 | 71 | func (l *DefaultLogger) Warnf(ctx context.Context, format string, args ...interface{}) { 72 | content := fmt.Sprintf(format, args...) 73 | logStr, _ := (&LogData{Level: LevelWarn, Content: content}).EncodeToStr() 74 | fmt.Println(string(logStr)) 75 | } 76 | 77 | func (l *DefaultLogger) Errorf(ctx context.Context, format string, args ...interface{}) { 78 | content := fmt.Sprintf(format, args...) 79 | logStr, _ := (&LogData{Level: LevelError, Content: content}).EncodeToStr() 80 | fmt.Println(string(logStr)) 81 | } 82 | -------------------------------------------------------------------------------- /examples/tcp_fixed_head/tcp_fixed_head_server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "encoding/binary" 6 | "flag" 7 | "fmt" 8 | "net" 9 | "strconv" 10 | "strings" 11 | "time" 12 | 13 | "github.com/cclehui/server_on_gnet/commonutil" 14 | "github.com/cclehui/server_on_gnet/tcp_fixed_head" 15 | "github.com/panjf2000/gnet/v2" 16 | ) 17 | 18 | // 网络编程 19 | // tcp server 简单的 固定头部长度协议 20 | func main() { 21 | 22 | var port int 23 | var multicore bool 24 | 25 | // Example command: go run main.go --port 2333 --multicore true 26 | flag.IntVar(&port, "port", 5000, "server port") 27 | flag.BoolVar(&multicore, "multicore", true, "multicore") 28 | flag.Parse() 29 | 30 | tcpServer := tcp_fixed_head.NewTCPFixHeadServer(port) 31 | ctx := context.Background() 32 | 33 | go func() { 34 | for { 35 | commonutil.GetLogger().Infof(ctx, "当前连接数量:%d", tcpServer.ConnNum) 36 | 37 | time.Sleep(time.Second * 1) 38 | } 39 | }() 40 | 41 | go func() { 42 | for i := 0; i < 4; i++ { 43 | go func() { 44 | tcpFHTestClient(ctx, port) 45 | }() 46 | } 47 | }() 48 | 49 | options := []gnet.Option{ 50 | gnet.WithReusePort(true), 51 | gnet.WithMulticore(multicore), 52 | gnet.WithTCPKeepAlive(time.Second * 90), 53 | } 54 | 55 | err := tcp_fixed_head.Run(tcpServer, fmt.Sprintf("tcp://:%d", port), options...) 56 | if err != nil { 57 | commonutil.GetLogger().Errorf(ctx, "启动失败:%+v", err) 58 | } 59 | } 60 | 61 | // 测试 client 62 | func tcpFHTestClient(ctx context.Context, port int) { 63 | time.Sleep(time.Second * 3) 64 | 65 | conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%d", port)) 66 | //_, err := net.Dial("tcp", fmt.Sprintf("localhost:%d", port)) 67 | 68 | if err != nil { 69 | commonutil.GetLogger().Errorf(ctx, "tcpFHTestClient, Dail error:%v", err) 70 | } 71 | 72 | protocol := tcp_fixed_head.NewTCPFixHeadProtocol() 73 | 74 | for i := 1; i <= 3; i++ { 75 | //for i := 1; i <= 2; i++ { 76 | data := strings.Repeat(strconv.Itoa(i), i) 77 | data = data + "abc" 78 | 79 | if i == 2 { 80 | badData := []byte("xxx") 81 | err2 := binary.Write(conn, binary.BigEndian, badData) 82 | fmt.Println("发送干扰数据, ", err2) 83 | } 84 | 85 | //fmt.Println("发送数据\t", data) 86 | 87 | //直接encode 并发送 88 | //protocal.EncodeWrite(tcp_fixed_head.ACTION_PING, []byte(data), conn) 89 | 90 | //返回encode 的数据, 然后发送 91 | encodedData, _ := protocol.EncodeData(tcp_fixed_head.ACTION_PING, []byte(data)) 92 | commonutil.GetLogger().Infof(ctx, "client 发送数据,%s", data) 93 | 94 | conn.Write(encodedData) 95 | 96 | time.Sleep(time.Second * 1) 97 | } 98 | 99 | commonutil.GetLogger().Infof(ctx, "开始获取服务端返回的数据......") 100 | 101 | for { 102 | time.Sleep(time.Second * 1) 103 | response, err := protocol.ClientDecode(conn) 104 | 105 | if err != nil { 106 | commonutil.GetLogger().Errorf(ctx, "获取服务端数据异常, %v", err) 107 | continue 108 | } 109 | 110 | commonutil.GetLogger().Infof(ctx, "服务端返回的数据, %v, data:%s", response, string(response.Data)) 111 | 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /examples/websocket/websocket_server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "log" 7 | "net/http" 8 | "time" 9 | 10 | "github.com/cclehui/server_on_gnet/commonutil" 11 | "github.com/cclehui/server_on_gnet/websocket" 12 | "github.com/panjf2000/gnet/v2" 13 | ) 14 | 15 | func wsHome(w http.ResponseWriter, r *http.Request) { 16 | //websocket.ClientTemplate.Execute(w, "ws://"+r.Host+"/echo") 17 | websocket.ClientTemplate.Execute(w, "ws://192.168.126.139:8081") 18 | } 19 | 20 | func main() { 21 | ctx := context.Background() 22 | 23 | go func() { 24 | 25 | //处理 websocket 协议的tcp服务监听在 8081端口上 26 | port := 8081 27 | addr := fmt.Sprintf(":%d", port) 28 | 29 | tcpServer := websocket.NewEchoServer(addr) 30 | 31 | go func() { 32 | for { 33 | fmt.Println("当前连接数量:", tcpServer.ConnNum) 34 | 35 | time.Sleep(time.Second * 2) 36 | } 37 | 38 | }() 39 | 40 | options := []gnet.Option{ 41 | gnet.WithReusePort(true), 42 | gnet.WithMulticore(true), 43 | } 44 | log.Fatal(gnet.Run(tcpServer, fmt.Sprintf("tcp://:%d", port), options...)) 45 | 46 | }() 47 | 48 | //var addr = flag.String("addr", "localhost:8080", "http service address") 49 | addr := "0.0.0.0:8080" 50 | 51 | commonutil.GetLogger().Infof(ctx, "http server for websocket client is listen at :%s\n", addr) 52 | 53 | http.HandleFunc("/", wsHome) 54 | log.Fatal(http.ListenAndServe(addr, nil)) 55 | 56 | } 57 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/cclehui/server_on_gnet 2 | 3 | go 1.19 4 | 5 | require ( 6 | github.com/gobwas/ws v1.1.0 7 | github.com/golang/protobuf v1.3.2 8 | github.com/panjf2000/ants/v2 v2.4.8 9 | github.com/panjf2000/gnet/v2 v2.2.0 10 | github.com/pkg/errors v0.8.1 11 | golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4 12 | google.golang.org/grpc v1.25.1 13 | ) 14 | 15 | require ( 16 | github.com/gobwas/httphead v0.1.0 // indirect 17 | github.com/gobwas/pool v0.2.1 // indirect 18 | go.uber.org/atomic v1.9.0 // indirect 19 | go.uber.org/multierr v1.7.0 // indirect 20 | go.uber.org/zap v1.21.0 // indirect 21 | golang.org/x/sys v0.0.0-20220224120231-95c6836cb0e7 // indirect 22 | golang.org/x/text v0.3.3 // indirect 23 | google.golang.org/genproto v0.0.0-20190927181202-20e1ac93f88c // indirect 24 | gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect 25 | ) 26 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= 2 | github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= 3 | github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= 4 | github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= 5 | github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= 6 | github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= 7 | github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= 8 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 9 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 10 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 11 | github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= 12 | github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= 13 | github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU= 14 | github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM= 15 | github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og= 16 | github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= 17 | github.com/gobwas/ws v1.1.0 h1:7RFti/xnNkMJnrK7D1yQ/iCIB5OrrY/54/H930kIbHA= 18 | github.com/gobwas/ws v1.1.0/go.mod h1:nzvNcVha5eUziGrbxFCo6qFIojQHjJV5cLYIbezhfL0= 19 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= 20 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= 21 | github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= 22 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 23 | github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= 24 | github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 25 | github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= 26 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 27 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 28 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 29 | github.com/panjf2000/ants/v2 v2.4.8 h1:JgTbolX6K6RreZ4+bfctI0Ifs+3mrE5BIHudQxUDQ9k= 30 | github.com/panjf2000/ants/v2 v2.4.8/go.mod h1:f6F0NZVFsGCp5A7QW/Zj/m92atWwOkY0OIhFxRNFr4A= 31 | github.com/panjf2000/gnet/v2 v2.2.0 h1:+6itXhRlHJpv5UGAyN1DebHzK1l0GbZMOsg2Spb1VS0= 32 | github.com/panjf2000/gnet/v2 v2.2.0/go.mod h1:unWr2B4jF0DQPJH3GsXBGQiDcAamM6+Pf5FiK705kc4= 33 | github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= 34 | github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 35 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 36 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 37 | github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= 38 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 39 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= 40 | github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= 41 | github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= 42 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 43 | github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= 44 | github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= 45 | github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= 46 | go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= 47 | go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE= 48 | go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= 49 | go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI= 50 | go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= 51 | go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= 52 | go.uber.org/multierr v1.7.0 h1:zaiO/rmgFjbmCXdSYJWQcdvOCsthmdaHfr3Gm2Kx4Ec= 53 | go.uber.org/multierr v1.7.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak= 54 | go.uber.org/zap v1.21.0 h1:WefMeulhovoZ2sYXz7st6K0sLj7bBhpiFaud4r4zST8= 55 | go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw= 56 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 57 | golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 58 | golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= 59 | golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= 60 | golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= 61 | golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= 62 | golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= 63 | golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= 64 | golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 65 | golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 66 | golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 67 | golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 68 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 69 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 70 | golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4 h1:4nGaVu0QrbjT/AK2PRLuQfQuh6DJve+pELhqTdAj3x0= 71 | golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= 72 | golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= 73 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 74 | golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 75 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 76 | golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 77 | golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 78 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 79 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 80 | golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 81 | golang.org/x/sys v0.0.0-20201207223542-d4d67f95c62d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 82 | golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 83 | golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 84 | golang.org/x/sys v0.0.0-20220224120231-95c6836cb0e7 h1:BXxu8t6QN0G1uff4bzZzSkpsax8+ALqTGUtz08QrV00= 85 | golang.org/x/sys v0.0.0-20220224120231-95c6836cb0e7/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 86 | golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= 87 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 88 | golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k= 89 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 90 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 91 | golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 92 | golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= 93 | golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= 94 | golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= 95 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 96 | golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= 97 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 98 | golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 99 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 100 | google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= 101 | google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= 102 | google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= 103 | google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= 104 | google.golang.org/genproto v0.0.0-20190927181202-20e1ac93f88c h1:hrpEMCZ2O7DR5gC1n2AJGVhrwiEjOi35+jxtIuZpTMo= 105 | google.golang.org/genproto v0.0.0-20190927181202-20e1ac93f88c/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= 106 | google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= 107 | google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= 108 | google.golang.org/grpc v1.25.1 h1:wdKvqQk7IttEw92GoRyKG2IDrUIpgpj6H6m81yfeMW0= 109 | google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= 110 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 111 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 112 | gopkg.in/natefinch/lumberjack.v2 v2.0.0 h1:1Lc07Kr7qY4U2YPouBjpCLxpiyxIVoxqXgkXLknAOE8= 113 | gopkg.in/natefinch/lumberjack.v2 v2.0.0/go.mod h1:l0ndWWf7gzL7RNwBG7wST/UCcT4T24xpD6X8LsfU/+k= 114 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 115 | gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 116 | gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= 117 | gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 118 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 119 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= 120 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 121 | honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= 122 | honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= 123 | -------------------------------------------------------------------------------- /grpc/grpc_temp_client.go: -------------------------------------------------------------------------------- 1 | package main 2 | -------------------------------------------------------------------------------- /grpc/grpc_temp_server.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "context" 6 | "fmt" 7 | "log" 8 | "net" 9 | "runtime" 10 | "strconv" 11 | "time" 12 | 13 | "github.com/cclehui/server_on_gnet/grpc/protobuf" 14 | "google.golang.org/grpc" 15 | "google.golang.org/grpc/keepalive" 16 | ) 17 | 18 | const ( 19 | port = ":50051" 20 | ) 21 | 22 | func getGoroutineID() uint64 { 23 | b := make([]byte, 64) 24 | runtime.Stack(b, false) 25 | b = bytes.TrimPrefix(b, []byte("goroutine ")) 26 | b = b[:bytes.IndexByte(b, ' ')] 27 | n, _ := strconv.ParseUint(string(b), 10, 64) 28 | return n 29 | } 30 | 31 | // server is used to implement helloworld.GreeterServer. 32 | type helloServer struct { 33 | } 34 | 35 | // SayHello implements helloworld.GreeterServer 36 | func (s *helloServer) SayHello(ctx context.Context, in *protobuf.HelloRequest) (*protobuf.HelloReply, error) { 37 | groutineId := getGoroutineID() 38 | log.Printf("groutineId:%d, Received: %v", groutineId, in.GetName()) 39 | time.Sleep(time.Second * 5) 40 | log.Printf("groutineId:%d, Response: Hello %v", groutineId, in.GetName()) 41 | return &protobuf.HelloReply{Message: "Hello " + in.GetName()}, nil 42 | } 43 | 44 | func startGrpcServer() { 45 | 46 | lis, err := net.Listen("tcp", port) 47 | if err != nil { 48 | log.Fatalf("failed to listen: %v, port:%v", err, port) 49 | } 50 | 51 | var kaep = keepalive.EnforcementPolicy{ 52 | MinTime: 5 * time.Second, // If a client pings more than once every 5 seconds, terminate the connection 53 | PermitWithoutStream: true, // Allow pings even when there are no active streams 54 | } 55 | 56 | var kasp = keepalive.ServerParameters{ 57 | MaxConnectionIdle: 15 * time.Second, // If a client is idle for 15 seconds, send a GOAWAY 58 | MaxConnectionAge: 30 * time.Second, // If any connection is alive for more than 30 seconds, send a GOAWAY 59 | MaxConnectionAgeGrace: 5 * time.Second, // Allow 5 seconds for pending RPCs to complete before forcibly closing connections 60 | Time: 5 * time.Second, // Ping the client if it is idle for 5 seconds to ensure the connection is still active 61 | Timeout: 1 * time.Second, // Wait 1 second for the ping ack before assuming the connection is dead 62 | } 63 | 64 | server := grpc.NewServer(grpc.KeepaliveEnforcementPolicy(kaep), grpc.KeepaliveParams(kasp)) 65 | 66 | protobuf.RegisterGreeterServer(server, &helloServer{}) 67 | 68 | log.Printf("grpc 服务启动, tcp port:%v\n", port) 69 | 70 | if err := server.Serve(lis); err != nil { 71 | log.Fatalf("failed to serve: %v", err) 72 | } 73 | 74 | } 75 | 76 | func main() { 77 | go func() { // client 78 | time.Sleep(time.Second * 2) 79 | 80 | clientTest() 81 | }() 82 | 83 | //启动 grpc server 84 | startGrpcServer() 85 | } 86 | 87 | /*******************/ 88 | func clientTest() { 89 | serverPort := ":50051" 90 | 91 | serverAddress := fmt.Sprintf("localhost%v", serverPort) 92 | 93 | /* 94 | keepaliveParam := keepalive.ClientParameters{} 95 | keepaliveParam.Time = time.Second * 10 96 | keepaliveParam.Timeout = time.Second * 2 97 | keepaliveParam.PermitWithoutStream = true 98 | */ 99 | var kacp = keepalive.ClientParameters{ 100 | Time: 10 * time.Second, // send pings every 10 seconds if there is no activity 101 | Timeout: time.Second, // wait 1 second for ping ack before considering the connection dead 102 | PermitWithoutStream: true, // send pings even without active streams 103 | } 104 | 105 | conn, err := grpc.Dial(serverAddress, grpc.WithInsecure(), grpc.WithKeepaliveParams(kacp)) 106 | if err != nil { 107 | log.Printf("连接服务端失败, %v\n", err) 108 | return 109 | } 110 | 111 | log.Printf("连接服务端成功, %v\n", conn.Target()) 112 | defer conn.Close() 113 | 114 | for i := 1; i < 4; i++ { 115 | go func(num int) { 116 | name := fmt.Sprintf("cclehui_%d", num) 117 | for { 118 | client := protobuf.NewGreeterClient(conn) 119 | 120 | request := &protobuf.HelloRequest{Name: name} 121 | 122 | reply, err2 := client.SayHello(context.Background(), request) 123 | 124 | if err2 != nil { 125 | log.Printf("client:%d, 调用rpc方法失败, %v\n", num, err2) 126 | return 127 | } 128 | 129 | log.Printf("client:%d, 调用rpc方法成功, server reply:%v\n", num, reply.GetMessage()) 130 | time.Sleep(time.Second * 1) 131 | } 132 | }(i) 133 | } 134 | select {} 135 | } 136 | -------------------------------------------------------------------------------- /grpc/protobuf/hello.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // source: hello.proto 3 | 4 | package protobuf 5 | 6 | import ( 7 | context "context" 8 | fmt "fmt" 9 | proto "github.com/golang/protobuf/proto" 10 | grpc "google.golang.org/grpc" 11 | codes "google.golang.org/grpc/codes" 12 | status "google.golang.org/grpc/status" 13 | math "math" 14 | ) 15 | 16 | // Reference imports to suppress errors if they are not otherwise used. 17 | var _ = proto.Marshal 18 | var _ = fmt.Errorf 19 | var _ = math.Inf 20 | 21 | // This is a compile-time assertion to ensure that this generated file 22 | // is compatible with the proto package it is being compiled against. 23 | // A compilation error at this line likely means your copy of the 24 | // proto package needs to be updated. 25 | const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package 26 | 27 | // 包含用户名的请求信息 28 | type HelloRequest struct { 29 | Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` 30 | XXX_NoUnkeyedLiteral struct{} `json:"-"` 31 | XXX_unrecognized []byte `json:"-"` 32 | XXX_sizecache int32 `json:"-"` 33 | } 34 | 35 | func (m *HelloRequest) Reset() { *m = HelloRequest{} } 36 | func (m *HelloRequest) String() string { return proto.CompactTextString(m) } 37 | func (*HelloRequest) ProtoMessage() {} 38 | func (*HelloRequest) Descriptor() ([]byte, []int) { 39 | return fileDescriptor_61ef911816e0a8ce, []int{0} 40 | } 41 | 42 | func (m *HelloRequest) XXX_Unmarshal(b []byte) error { 43 | return xxx_messageInfo_HelloRequest.Unmarshal(m, b) 44 | } 45 | func (m *HelloRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 46 | return xxx_messageInfo_HelloRequest.Marshal(b, m, deterministic) 47 | } 48 | func (m *HelloRequest) XXX_Merge(src proto.Message) { 49 | xxx_messageInfo_HelloRequest.Merge(m, src) 50 | } 51 | func (m *HelloRequest) XXX_Size() int { 52 | return xxx_messageInfo_HelloRequest.Size(m) 53 | } 54 | func (m *HelloRequest) XXX_DiscardUnknown() { 55 | xxx_messageInfo_HelloRequest.DiscardUnknown(m) 56 | } 57 | 58 | var xxx_messageInfo_HelloRequest proto.InternalMessageInfo 59 | 60 | func (m *HelloRequest) GetName() string { 61 | if m != nil { 62 | return m.Name 63 | } 64 | return "" 65 | } 66 | 67 | // 服务端响应信息 68 | type HelloReply struct { 69 | Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` 70 | XXX_NoUnkeyedLiteral struct{} `json:"-"` 71 | XXX_unrecognized []byte `json:"-"` 72 | XXX_sizecache int32 `json:"-"` 73 | } 74 | 75 | func (m *HelloReply) Reset() { *m = HelloReply{} } 76 | func (m *HelloReply) String() string { return proto.CompactTextString(m) } 77 | func (*HelloReply) ProtoMessage() {} 78 | func (*HelloReply) Descriptor() ([]byte, []int) { 79 | return fileDescriptor_61ef911816e0a8ce, []int{1} 80 | } 81 | 82 | func (m *HelloReply) XXX_Unmarshal(b []byte) error { 83 | return xxx_messageInfo_HelloReply.Unmarshal(m, b) 84 | } 85 | func (m *HelloReply) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 86 | return xxx_messageInfo_HelloReply.Marshal(b, m, deterministic) 87 | } 88 | func (m *HelloReply) XXX_Merge(src proto.Message) { 89 | xxx_messageInfo_HelloReply.Merge(m, src) 90 | } 91 | func (m *HelloReply) XXX_Size() int { 92 | return xxx_messageInfo_HelloReply.Size(m) 93 | } 94 | func (m *HelloReply) XXX_DiscardUnknown() { 95 | xxx_messageInfo_HelloReply.DiscardUnknown(m) 96 | } 97 | 98 | var xxx_messageInfo_HelloReply proto.InternalMessageInfo 99 | 100 | func (m *HelloReply) GetMessage() string { 101 | if m != nil { 102 | return m.Message 103 | } 104 | return "" 105 | } 106 | 107 | func init() { 108 | proto.RegisterType((*HelloRequest)(nil), "protobuf.HelloRequest") 109 | proto.RegisterType((*HelloReply)(nil), "protobuf.HelloReply") 110 | } 111 | 112 | func init() { proto.RegisterFile("hello.proto", fileDescriptor_61ef911816e0a8ce) } 113 | 114 | var fileDescriptor_61ef911816e0a8ce = []byte{ 115 | // 139 bytes of a gzipped FileDescriptorProto 116 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0xce, 0x48, 0xcd, 0xc9, 117 | 0xc9, 0xd7, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0xe2, 0x00, 0x53, 0x49, 0xa5, 0x69, 0x4a, 0x4a, 118 | 0x5c, 0x3c, 0x1e, 0x20, 0x89, 0xa0, 0xd4, 0xc2, 0xd2, 0xd4, 0xe2, 0x12, 0x21, 0x21, 0x2e, 0x96, 119 | 0xbc, 0xc4, 0xdc, 0x54, 0x09, 0x46, 0x05, 0x46, 0x0d, 0xce, 0x20, 0x30, 0x5b, 0x49, 0x8d, 0x8b, 120 | 0x0b, 0xaa, 0xa6, 0x20, 0xa7, 0x52, 0x48, 0x82, 0x8b, 0x3d, 0x37, 0xb5, 0xb8, 0x38, 0x31, 0x1d, 121 | 0xa6, 0x08, 0xc6, 0x35, 0x72, 0xe5, 0x62, 0x77, 0x2f, 0x4a, 0x4d, 0x2d, 0x49, 0x2d, 0x12, 0xb2, 122 | 0xe2, 0xe2, 0x08, 0x4e, 0xac, 0x04, 0xeb, 0x12, 0x12, 0xd3, 0x83, 0xd9, 0xa6, 0x87, 0x6c, 0x95, 123 | 0x94, 0x08, 0x86, 0x78, 0x41, 0x4e, 0xa5, 0x12, 0x43, 0x12, 0x1b, 0x58, 0xd8, 0x18, 0x10, 0x00, 124 | 0x00, 0xff, 0xff, 0xa5, 0x2d, 0xe1, 0x05, 0xb2, 0x00, 0x00, 0x00, 125 | } 126 | 127 | // Reference imports to suppress errors if they are not otherwise used. 128 | var _ context.Context 129 | var _ grpc.ClientConn 130 | 131 | // This is a compile-time assertion to ensure that this generated file 132 | // is compatible with the grpc package it is being compiled against. 133 | const _ = grpc.SupportPackageIsVersion4 134 | 135 | // GreeterClient is the client API for Greeter service. 136 | // 137 | // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. 138 | type GreeterClient interface { 139 | // 服务端返馈信息方法 140 | SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) 141 | } 142 | 143 | type greeterClient struct { 144 | cc *grpc.ClientConn 145 | } 146 | 147 | func NewGreeterClient(cc *grpc.ClientConn) GreeterClient { 148 | return &greeterClient{cc} 149 | } 150 | 151 | func (c *greeterClient) SayHello(ctx context.Context, in *HelloRequest, opts ...grpc.CallOption) (*HelloReply, error) { 152 | out := new(HelloReply) 153 | err := c.cc.Invoke(ctx, "/protobuf.Greeter/SayHello", in, out, opts...) 154 | if err != nil { 155 | return nil, err 156 | } 157 | return out, nil 158 | } 159 | 160 | // GreeterServer is the server API for Greeter service. 161 | type GreeterServer interface { 162 | // 服务端返馈信息方法 163 | SayHello(context.Context, *HelloRequest) (*HelloReply, error) 164 | } 165 | 166 | // UnimplementedGreeterServer can be embedded to have forward compatible implementations. 167 | type UnimplementedGreeterServer struct { 168 | } 169 | 170 | func (*UnimplementedGreeterServer) SayHello(ctx context.Context, req *HelloRequest) (*HelloReply, error) { 171 | return nil, status.Errorf(codes.Unimplemented, "method SayHello not implemented") 172 | } 173 | 174 | func RegisterGreeterServer(s *grpc.Server, srv GreeterServer) { 175 | s.RegisterService(&_Greeter_serviceDesc, srv) 176 | } 177 | 178 | func _Greeter_SayHello_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { 179 | in := new(HelloRequest) 180 | if err := dec(in); err != nil { 181 | return nil, err 182 | } 183 | if interceptor == nil { 184 | return srv.(GreeterServer).SayHello(ctx, in) 185 | } 186 | info := &grpc.UnaryServerInfo{ 187 | Server: srv, 188 | FullMethod: "/protobuf.Greeter/SayHello", 189 | } 190 | handler := func(ctx context.Context, req interface{}) (interface{}, error) { 191 | return srv.(GreeterServer).SayHello(ctx, req.(*HelloRequest)) 192 | } 193 | return interceptor(ctx, in, info, handler) 194 | } 195 | 196 | var _Greeter_serviceDesc = grpc.ServiceDesc{ 197 | ServiceName: "protobuf.Greeter", 198 | HandlerType: (*GreeterServer)(nil), 199 | Methods: []grpc.MethodDesc{ 200 | { 201 | MethodName: "SayHello", 202 | Handler: _Greeter_SayHello_Handler, 203 | }, 204 | }, 205 | Streams: []grpc.StreamDesc{}, 206 | Metadata: "hello.proto", 207 | } 208 | -------------------------------------------------------------------------------- /grpc/protobuf/hello.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package protobuf; 3 | 4 | // 服务端定义 5 | service Greeter { 6 | // 服务端返馈信息方法 7 | rpc SayHello (HelloRequest) returns (HelloReply) {} 8 | } 9 | 10 | // 包含用户名的请求信息 11 | message HelloRequest { 12 | string name = 1; 13 | } 14 | 15 | // 服务端响应信息 16 | message HelloReply { 17 | string message = 1; 18 | } 19 | -------------------------------------------------------------------------------- /grpc/protobuf/temp.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-go. DO NOT EDIT. 2 | // source: temp.proto 3 | 4 | package protobuf 5 | 6 | import ( 7 | fmt "fmt" 8 | proto "github.com/golang/protobuf/proto" 9 | timestamp "github.com/golang/protobuf/ptypes/timestamp" 10 | math "math" 11 | ) 12 | 13 | // Reference imports to suppress errors if they are not otherwise used. 14 | var _ = proto.Marshal 15 | var _ = fmt.Errorf 16 | var _ = math.Inf 17 | 18 | // This is a compile-time assertion to ensure that this generated file 19 | // is compatible with the proto package it is being compiled against. 20 | // A compilation error at this line likely means your copy of the 21 | // proto package needs to be updated. 22 | const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package 23 | 24 | type Person_PhoneType int32 25 | 26 | const ( 27 | Person_MOBILE Person_PhoneType = 0 28 | Person_HOME Person_PhoneType = 1 29 | Person_WORK Person_PhoneType = 2 30 | ) 31 | 32 | var Person_PhoneType_name = map[int32]string{ 33 | 0: "MOBILE", 34 | 1: "HOME", 35 | 2: "WORK", 36 | } 37 | 38 | var Person_PhoneType_value = map[string]int32{ 39 | "MOBILE": 0, 40 | "HOME": 1, 41 | "WORK": 2, 42 | } 43 | 44 | func (x Person_PhoneType) String() string { 45 | return proto.EnumName(Person_PhoneType_name, int32(x)) 46 | } 47 | 48 | func (Person_PhoneType) EnumDescriptor() ([]byte, []int) { 49 | return fileDescriptor_d4ff44c374d44cb2, []int{0, 0} 50 | } 51 | 52 | type Person struct { 53 | Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` 54 | Id int32 `protobuf:"varint,2,opt,name=id,proto3" json:"id,omitempty"` 55 | Email string `protobuf:"bytes,3,opt,name=email,proto3" json:"email,omitempty"` 56 | Phones []*Person_PhoneNumber `protobuf:"bytes,4,rep,name=phones,proto3" json:"phones,omitempty"` 57 | LastUpdated *timestamp.Timestamp `protobuf:"bytes,5,opt,name=last_updated,json=lastUpdated,proto3" json:"last_updated,omitempty"` 58 | XXX_NoUnkeyedLiteral struct{} `json:"-"` 59 | XXX_unrecognized []byte `json:"-"` 60 | XXX_sizecache int32 `json:"-"` 61 | } 62 | 63 | func (m *Person) Reset() { *m = Person{} } 64 | func (m *Person) String() string { return proto.CompactTextString(m) } 65 | func (*Person) ProtoMessage() {} 66 | func (*Person) Descriptor() ([]byte, []int) { 67 | return fileDescriptor_d4ff44c374d44cb2, []int{0} 68 | } 69 | 70 | func (m *Person) XXX_Unmarshal(b []byte) error { 71 | return xxx_messageInfo_Person.Unmarshal(m, b) 72 | } 73 | func (m *Person) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 74 | return xxx_messageInfo_Person.Marshal(b, m, deterministic) 75 | } 76 | func (m *Person) XXX_Merge(src proto.Message) { 77 | xxx_messageInfo_Person.Merge(m, src) 78 | } 79 | func (m *Person) XXX_Size() int { 80 | return xxx_messageInfo_Person.Size(m) 81 | } 82 | func (m *Person) XXX_DiscardUnknown() { 83 | xxx_messageInfo_Person.DiscardUnknown(m) 84 | } 85 | 86 | var xxx_messageInfo_Person proto.InternalMessageInfo 87 | 88 | func (m *Person) GetName() string { 89 | if m != nil { 90 | return m.Name 91 | } 92 | return "" 93 | } 94 | 95 | func (m *Person) GetId() int32 { 96 | if m != nil { 97 | return m.Id 98 | } 99 | return 0 100 | } 101 | 102 | func (m *Person) GetEmail() string { 103 | if m != nil { 104 | return m.Email 105 | } 106 | return "" 107 | } 108 | 109 | func (m *Person) GetPhones() []*Person_PhoneNumber { 110 | if m != nil { 111 | return m.Phones 112 | } 113 | return nil 114 | } 115 | 116 | func (m *Person) GetLastUpdated() *timestamp.Timestamp { 117 | if m != nil { 118 | return m.LastUpdated 119 | } 120 | return nil 121 | } 122 | 123 | type Person_PhoneNumber struct { 124 | Number string `protobuf:"bytes,1,opt,name=number,proto3" json:"number,omitempty"` 125 | Type Person_PhoneType `protobuf:"varint,2,opt,name=type,proto3,enum=protobuf.Person_PhoneType" json:"type,omitempty"` 126 | XXX_NoUnkeyedLiteral struct{} `json:"-"` 127 | XXX_unrecognized []byte `json:"-"` 128 | XXX_sizecache int32 `json:"-"` 129 | } 130 | 131 | func (m *Person_PhoneNumber) Reset() { *m = Person_PhoneNumber{} } 132 | func (m *Person_PhoneNumber) String() string { return proto.CompactTextString(m) } 133 | func (*Person_PhoneNumber) ProtoMessage() {} 134 | func (*Person_PhoneNumber) Descriptor() ([]byte, []int) { 135 | return fileDescriptor_d4ff44c374d44cb2, []int{0, 0} 136 | } 137 | 138 | func (m *Person_PhoneNumber) XXX_Unmarshal(b []byte) error { 139 | return xxx_messageInfo_Person_PhoneNumber.Unmarshal(m, b) 140 | } 141 | func (m *Person_PhoneNumber) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 142 | return xxx_messageInfo_Person_PhoneNumber.Marshal(b, m, deterministic) 143 | } 144 | func (m *Person_PhoneNumber) XXX_Merge(src proto.Message) { 145 | xxx_messageInfo_Person_PhoneNumber.Merge(m, src) 146 | } 147 | func (m *Person_PhoneNumber) XXX_Size() int { 148 | return xxx_messageInfo_Person_PhoneNumber.Size(m) 149 | } 150 | func (m *Person_PhoneNumber) XXX_DiscardUnknown() { 151 | xxx_messageInfo_Person_PhoneNumber.DiscardUnknown(m) 152 | } 153 | 154 | var xxx_messageInfo_Person_PhoneNumber proto.InternalMessageInfo 155 | 156 | func (m *Person_PhoneNumber) GetNumber() string { 157 | if m != nil { 158 | return m.Number 159 | } 160 | return "" 161 | } 162 | 163 | func (m *Person_PhoneNumber) GetType() Person_PhoneType { 164 | if m != nil { 165 | return m.Type 166 | } 167 | return Person_MOBILE 168 | } 169 | 170 | // Our address book file is just one of these. 171 | type AddressBook struct { 172 | People []*Person `protobuf:"bytes,1,rep,name=people,proto3" json:"people,omitempty"` 173 | XXX_NoUnkeyedLiteral struct{} `json:"-"` 174 | XXX_unrecognized []byte `json:"-"` 175 | XXX_sizecache int32 `json:"-"` 176 | } 177 | 178 | func (m *AddressBook) Reset() { *m = AddressBook{} } 179 | func (m *AddressBook) String() string { return proto.CompactTextString(m) } 180 | func (*AddressBook) ProtoMessage() {} 181 | func (*AddressBook) Descriptor() ([]byte, []int) { 182 | return fileDescriptor_d4ff44c374d44cb2, []int{1} 183 | } 184 | 185 | func (m *AddressBook) XXX_Unmarshal(b []byte) error { 186 | return xxx_messageInfo_AddressBook.Unmarshal(m, b) 187 | } 188 | func (m *AddressBook) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { 189 | return xxx_messageInfo_AddressBook.Marshal(b, m, deterministic) 190 | } 191 | func (m *AddressBook) XXX_Merge(src proto.Message) { 192 | xxx_messageInfo_AddressBook.Merge(m, src) 193 | } 194 | func (m *AddressBook) XXX_Size() int { 195 | return xxx_messageInfo_AddressBook.Size(m) 196 | } 197 | func (m *AddressBook) XXX_DiscardUnknown() { 198 | xxx_messageInfo_AddressBook.DiscardUnknown(m) 199 | } 200 | 201 | var xxx_messageInfo_AddressBook proto.InternalMessageInfo 202 | 203 | func (m *AddressBook) GetPeople() []*Person { 204 | if m != nil { 205 | return m.People 206 | } 207 | return nil 208 | } 209 | 210 | func init() { 211 | proto.RegisterEnum("protobuf.Person_PhoneType", Person_PhoneType_name, Person_PhoneType_value) 212 | proto.RegisterType((*Person)(nil), "protobuf.Person") 213 | proto.RegisterType((*Person_PhoneNumber)(nil), "protobuf.Person.PhoneNumber") 214 | proto.RegisterType((*AddressBook)(nil), "protobuf.AddressBook") 215 | } 216 | 217 | func init() { proto.RegisterFile("temp.proto", fileDescriptor_d4ff44c374d44cb2) } 218 | 219 | var fileDescriptor_d4ff44c374d44cb2 = []byte{ 220 | // 302 bytes of a gzipped FileDescriptorProto 221 | 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0x90, 0x41, 0x4b, 0xfb, 0x40, 222 | 0x10, 0xc5, 0xff, 0x49, 0xd3, 0xd0, 0x4e, 0xfe, 0x94, 0x30, 0x88, 0x84, 0x20, 0x18, 0x7a, 0x0a, 223 | 0x08, 0x29, 0x54, 0xc1, 0x93, 0x07, 0x0b, 0x05, 0x45, 0x6b, 0xcb, 0xd2, 0xe2, 0x51, 0x52, 0x76, 224 | 0xac, 0xc1, 0x24, 0xbb, 0x64, 0x37, 0x87, 0x7e, 0x36, 0xbf, 0x9c, 0x64, 0x93, 0xa8, 0x88, 0xa7, 225 | 0x9d, 0x99, 0xf7, 0xe3, 0xcd, 0xdb, 0x01, 0xd0, 0x54, 0xc8, 0x44, 0x56, 0x42, 0x0b, 0x1c, 0x99, 226 | 0x67, 0x5f, 0xbf, 0x86, 0xe7, 0x07, 0x21, 0x0e, 0x39, 0xcd, 0xfa, 0xc1, 0x4c, 0x67, 0x05, 0x29, 227 | 0x9d, 0xf6, 0xe8, 0xf4, 0xc3, 0x06, 0x77, 0x43, 0x95, 0x12, 0x25, 0x22, 0x38, 0x65, 0x5a, 0x50, 228 | 0x60, 0x45, 0x56, 0x3c, 0x66, 0xa6, 0xc6, 0x09, 0xd8, 0x19, 0x0f, 0xec, 0xc8, 0x8a, 0x87, 0xcc, 229 | 0xce, 0x38, 0x9e, 0xc0, 0x90, 0x8a, 0x34, 0xcb, 0x83, 0x81, 0x81, 0xda, 0x06, 0xaf, 0xc0, 0x95, 230 | 0x6f, 0xa2, 0x24, 0x15, 0x38, 0xd1, 0x20, 0xf6, 0xe6, 0x67, 0x49, 0xbf, 0x2f, 0x69, 0xbd, 0x93, 231 | 0x4d, 0x23, 0x3f, 0xd5, 0xc5, 0x9e, 0x2a, 0xd6, 0xb1, 0x78, 0x03, 0xff, 0xf3, 0x54, 0xe9, 0x97, 232 | 0x5a, 0xf2, 0x54, 0x13, 0x0f, 0x86, 0x91, 0x15, 0x7b, 0xf3, 0x30, 0x69, 0x23, 0x7f, 0x5b, 0x6c, 233 | 0xfb, 0xc8, 0xcc, 0x6b, 0xf8, 0x5d, 0x8b, 0x87, 0x3b, 0xf0, 0x7e, 0xb8, 0xe2, 0x29, 0xb8, 0xa5, 234 | 0xa9, 0xba, 0xfc, 0x5d, 0x87, 0x09, 0x38, 0xfa, 0x28, 0xc9, 0xfc, 0x61, 0x32, 0x0f, 0xff, 0x4e, 235 | 0xb6, 0x3d, 0x4a, 0x62, 0x86, 0x9b, 0x5e, 0xc0, 0xf8, 0x6b, 0x84, 0x00, 0xee, 0x6a, 0xbd, 0xb8, 236 | 0x7f, 0x5c, 0xfa, 0xff, 0x70, 0x04, 0xce, 0xdd, 0x7a, 0xb5, 0xf4, 0xad, 0xa6, 0x7a, 0x5e, 0xb3, 237 | 0x07, 0xdf, 0x9e, 0x5e, 0x83, 0x77, 0xcb, 0x79, 0x45, 0x4a, 0x2d, 0x84, 0x78, 0xc7, 0x18, 0x5c, 238 | 0x49, 0x42, 0xe6, 0xcd, 0x0d, 0x9b, 0x3b, 0xf8, 0xbf, 0xb7, 0xb1, 0x4e, 0xdf, 0xbb, 0x46, 0xb8, 239 | 0xfc, 0x0c, 0x00, 0x00, 0xff, 0xff, 0x86, 0x88, 0x03, 0x1b, 0xb6, 0x01, 0x00, 0x00, 240 | } 241 | -------------------------------------------------------------------------------- /grpc/protobuf/temp.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | package protobuf; 3 | 4 | import "google/protobuf/timestamp.proto"; 5 | 6 | message Person { 7 | string name = 1; 8 | int32 id = 2; // Unique ID number for this person. 9 | string email = 3; 10 | 11 | enum PhoneType { 12 | MOBILE = 0; 13 | HOME = 1; 14 | WORK = 2; 15 | } 16 | 17 | message PhoneNumber { 18 | string number = 1; 19 | PhoneType type = 2; 20 | } 21 | 22 | repeated PhoneNumber phones = 4; 23 | 24 | google.protobuf.Timestamp last_updated = 5; 25 | } 26 | 27 | // Our address book file is just one of these. 28 | message AddressBook { 29 | repeated Person people = 1; 30 | } 31 | -------------------------------------------------------------------------------- /proto_temp.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/cclehui/server_on_gnet/grpc/protobuf" 7 | "github.com/golang/protobuf/proto" 8 | ) 9 | 10 | func main() { 11 | 12 | person := &protobuf.Person{} 13 | 14 | person.Name = "cclehui" 15 | 16 | person.Id = 1 17 | 18 | encoded, _ := proto.Marshal(person) 19 | 20 | fmt.Printf("encoded , %v\n", encoded) 21 | 22 | newPerson := &protobuf.Person{} 23 | 24 | proto.Unmarshal(encoded, newPerson) 25 | 26 | fmt.Printf("decoded , %v\n", newPerson) 27 | 28 | } 29 | -------------------------------------------------------------------------------- /tcp_fixed_head/config.go: -------------------------------------------------------------------------------- 1 | package tcp_fixed_head 2 | 3 | import ( 4 | "bytes" 5 | "sync" 6 | 7 | "github.com/pkg/errors" 8 | ) 9 | 10 | const ( 11 | DefaultAntsPoolSize = 1024 * 1024 12 | 13 | DefaultHeadLength = 8 14 | 15 | PROTOCOL_VERSION = 0x8001 //协议版本 dec 32769 16 | 17 | socketRingBufferSize = 1024 18 | 19 | //协议行为定义 20 | ACTION_PING = 0x0001 // ping行为 21 | ACTION_PONG = 0x0002 // pong行为 22 | ACTION_DATA = 0x00F0 // 业务行为 23 | 24 | ) 25 | 26 | var ErrProtocolVersion = errors.New("PROTOCOL_VERSION error") 27 | var ErrIncompletePacket = errors.New("incomplete packet") 28 | var ErrContext = errors.New("context error") 29 | 30 | var bytesBufferPool = sync.Pool{ 31 | New: func() any { 32 | return new(bytes.Buffer) 33 | }, 34 | } 35 | 36 | func isCorrectAction(actionType uint16) bool { 37 | switch actionType { 38 | case ACTION_PING, ACTION_PONG, ACTION_DATA: 39 | return true 40 | default: 41 | return false 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /tcp_fixed_head/handler.go: -------------------------------------------------------------------------------- 1 | package tcp_fixed_head 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/cclehui/server_on_gnet/commonutil" 7 | "github.com/panjf2000/gnet/v2" 8 | ) 9 | 10 | type ServerHandler func(ctx *HandlerContext) 11 | 12 | // 默认handler echo server 13 | var defaultHandler ServerHandler = func(ctx *HandlerContext) { 14 | if ctx.ProtocolData == nil { 15 | return 16 | } 17 | 18 | protocol := NewTCPFixHeadProtocol() 19 | 20 | switch ctx.ProtocolData.ActionType { 21 | case ACTION_PING: 22 | pongData, err := protocol.EncodeData(ACTION_PONG, 23 | []byte(fmt.Sprintf("pong, %s", string(ctx.ProtocolData.Data)))) 24 | if err != nil { 25 | commonutil.GetLogger().Infof(ctx, "server encode pong , %v, err:%v", pongData, err) 26 | } 27 | 28 | if ctx.Conn != nil { 29 | ctx.Conn.AsyncWrite(pongData, func(c gnet.Conn, err error) error { return nil }) 30 | } 31 | } 32 | 33 | commonutil.GetLogger().Infof(ctx, "服务端收到数据, data:%s", string(ctx.ProtocolData.Data)) 34 | } 35 | -------------------------------------------------------------------------------- /tcp_fixed_head/handler_context.go: -------------------------------------------------------------------------------- 1 | package tcp_fixed_head 2 | 3 | import ( 4 | "time" 5 | 6 | "github.com/panjf2000/gnet/v2" 7 | ) 8 | 9 | type HandlerContext struct { 10 | ProtocolData *ProtocolData 11 | 12 | Conn gnet.Conn 13 | 14 | server *TCPFixHeadServer 15 | } 16 | 17 | func (ctx *HandlerContext) Deadline() (deadline time.Time, ok bool) { 18 | return 19 | } 20 | 21 | func (ctx *HandlerContext) Done() <-chan struct{} { 22 | return nil 23 | } 24 | 25 | func (ctx *HandlerContext) Err() error { 26 | return nil 27 | } 28 | 29 | func (ctx *HandlerContext) Value(key interface{}) interface{} { 30 | return nil 31 | } 32 | -------------------------------------------------------------------------------- /tcp_fixed_head/protocal.go: -------------------------------------------------------------------------------- 1 | package tcp_fixed_head 2 | 3 | import ( 4 | "bytes" 5 | "encoding/binary" 6 | "fmt" 7 | "io" 8 | "net" 9 | 10 | "github.com/pkg/errors" 11 | 12 | "github.com/panjf2000/gnet/v2" 13 | ) 14 | 15 | type ProtocolData struct { 16 | Version uint16 //协议版本标识 17 | ActionType uint16 //行为定义 18 | DataLength uint32 19 | Data []byte 20 | 21 | //headDecode bool 22 | //Lock sync.Mutex 23 | } 24 | 25 | // 协议头长度 26 | func (p *ProtocolData) HeadLength() int { 27 | return DefaultHeadLength 28 | } 29 | 30 | type TCPFixHeadProtocol struct{} 31 | 32 | // new protocal 33 | func NewTCPFixHeadProtocol() *TCPFixHeadProtocol { 34 | return &TCPFixHeadProtocol{} 35 | } 36 | 37 | func (tcpfhp *TCPFixHeadProtocol) getHeadLength() int { 38 | return DefaultHeadLength 39 | } 40 | 41 | // server端 gnet input 数据 decode 42 | func (tcpfhp *TCPFixHeadProtocol) Decode(c gnet.Conn) (*ProtocolData, error) { 43 | curConContext := c.Context() 44 | 45 | if curConContext == nil { 46 | //解析协议 header 47 | tempBufferLength := c.InboundBuffered() // 当前已有多少数据 48 | if tempBufferLength < tcpfhp.getHeadLength() { // 不够头长度 49 | return nil, ErrIncompletePacket 50 | } 51 | 52 | headData, _ := c.Next(tcpfhp.getHeadLength()) 53 | 54 | newConContext := &ProtocolData{} 55 | 56 | //数据长度 57 | bytesBuffer := bytes.NewBuffer(headData) 58 | binary.Read(bytesBuffer, binary.BigEndian, &newConContext.Version) 59 | binary.Read(bytesBuffer, binary.BigEndian, &newConContext.ActionType) 60 | binary.Read(bytesBuffer, binary.BigEndian, &newConContext.DataLength) 61 | 62 | if newConContext.Version != PROTOCOL_VERSION || 63 | !isCorrectAction(newConContext.ActionType) { //非正常协议数据 64 | return nil, ErrProtocolVersion 65 | } 66 | 67 | c.SetContext(newConContext) 68 | } 69 | 70 | //解析协议数据 71 | if protocolData, ok := c.Context().(*ProtocolData); !ok { 72 | c.SetContext(nil) 73 | 74 | return nil, ErrContext 75 | } else { 76 | tempBufferLength := c.InboundBuffered() // 当前已有多少数据 77 | frameDataLength := int(protocolData.DataLength) 78 | 79 | if tempBufferLength < frameDataLength { 80 | return nil, ErrIncompletePacket 81 | } 82 | 83 | // 数据够了 84 | data, _ := c.Next(frameDataLength) 85 | 86 | copyData := make([]byte, frameDataLength) // 复制 87 | copy(copyData, data) 88 | 89 | protocolData.Data = copyData 90 | 91 | c.SetContext(nil) 92 | 93 | return protocolData, nil 94 | } 95 | } 96 | 97 | // 数据反解 98 | func (tcpfhp *TCPFixHeadProtocol) DecodeFrame(frame []byte) (*ProtocolData, error) { 99 | data := &ProtocolData{} 100 | //数据长度 101 | bytesBuffer := bytes.NewBuffer(frame) 102 | 103 | if err := binary.Read(bytesBuffer, binary.BigEndian, &data.Version); err != nil { 104 | return nil, err 105 | } 106 | 107 | if err := binary.Read(bytesBuffer, binary.BigEndian, &data.ActionType); err != nil { 108 | return nil, err 109 | } 110 | 111 | if err := binary.Read(bytesBuffer, binary.BigEndian, &data.DataLength); err != nil { 112 | return nil, err 113 | } 114 | 115 | data.Data = frame[tcpfhp.getHeadLength():] 116 | 117 | return data, nil 118 | } 119 | 120 | // client 端获取解包后的数据 121 | func (tcpfhp *TCPFixHeadProtocol) ClientDecode(rawConn net.Conn) (*ProtocolData, error) { 122 | newPackage := ProtocolData{} 123 | 124 | headData := make([]byte, tcpfhp.getHeadLength()) 125 | 126 | n, err := io.ReadFull(rawConn, headData) 127 | if n != tcpfhp.getHeadLength() { 128 | return nil, err 129 | } 130 | 131 | //数据长度 132 | bytesBuffer := bytes.NewBuffer(headData) 133 | binary.Read(bytesBuffer, binary.BigEndian, &newPackage.Version) 134 | binary.Read(bytesBuffer, binary.BigEndian, &newPackage.ActionType) 135 | binary.Read(bytesBuffer, binary.BigEndian, &newPackage.DataLength) 136 | 137 | if newPackage.DataLength < 1 { 138 | return &newPackage, nil 139 | } 140 | 141 | data := make([]byte, newPackage.DataLength) 142 | dataNum, err2 := io.ReadFull(rawConn, data) 143 | 144 | if uint32(dataNum) != newPackage.DataLength { 145 | return nil, errors.New(fmt.Sprintf("read data error, %v", err2)) 146 | } 147 | 148 | newPackage.Data = data 149 | 150 | return &newPackage, nil 151 | } 152 | 153 | // output 数据编码 154 | func (tcpfhp *TCPFixHeadProtocol) EncodeWrite(actionType uint16, data []byte, conn net.Conn) error { 155 | 156 | if conn == nil { 157 | return errors.New("con 为空") 158 | } 159 | 160 | pdata := ProtocolData{} 161 | pdata.Version = PROTOCOL_VERSION 162 | pdata.ActionType = actionType 163 | pdata.DataLength = uint32(len(data)) 164 | pdata.Data = data 165 | 166 | if err := binary.Write(conn, binary.BigEndian, &pdata.Version); err != nil { 167 | return errors.New(fmt.Sprintf("encodeWrite version error , %v", err)) 168 | } 169 | 170 | if err := binary.Write(conn, binary.BigEndian, &pdata.ActionType); err != nil { 171 | return errors.New(fmt.Sprintf("encodeWrite type error , %v", err)) 172 | } 173 | 174 | if err := binary.Write(conn, binary.BigEndian, &pdata.DataLength); err != nil { 175 | return errors.New(fmt.Sprintf("encodeWrite datalength error , %v", err)) 176 | } 177 | 178 | if pdata.DataLength > 0 { 179 | if err := binary.Write(conn, binary.BigEndian, &pdata.Data); err != nil { 180 | return errors.New(fmt.Sprintf("encodeWrite data error , %v", err)) 181 | } 182 | } 183 | 184 | return nil 185 | } 186 | 187 | func (tcpfhp *TCPFixHeadProtocol) Encode(c gnet.Conn, buf []byte) ([]byte, error) { 188 | return buf, nil 189 | } 190 | 191 | // 数据编码 192 | func (tcpfhp *TCPFixHeadProtocol) EncodeData(actionType uint16, data []byte) ([]byte, error) { 193 | pdata := ProtocolData{} 194 | pdata.Version = PROTOCOL_VERSION 195 | pdata.ActionType = actionType 196 | pdata.DataLength = uint32(len(data)) 197 | pdata.Data = data 198 | 199 | result := make([]byte, 0) 200 | 201 | buffer := bytes.NewBuffer(result) 202 | 203 | if err := binary.Write(buffer, binary.BigEndian, &pdata.Version); err != nil { 204 | return nil, errors.New(fmt.Sprintf("encode version error , %v", err)) 205 | } 206 | 207 | if err := binary.Write(buffer, binary.BigEndian, &pdata.ActionType); err != nil { 208 | return nil, errors.New(fmt.Sprintf("encode type error , %v", err)) 209 | } 210 | 211 | if err := binary.Write(buffer, binary.BigEndian, &pdata.DataLength); err != nil { 212 | return nil, errors.New(fmt.Sprintf("encode datalength error , %v", err)) 213 | } 214 | 215 | if pdata.DataLength > 0 { 216 | if err := binary.Write(buffer, binary.BigEndian, &pdata.Data); err != nil { 217 | return nil, errors.New(fmt.Sprintf("encode data error , %v", err)) 218 | } 219 | } 220 | 221 | return buffer.Bytes(), nil 222 | } 223 | -------------------------------------------------------------------------------- /tcp_fixed_head/server.go: -------------------------------------------------------------------------------- 1 | package tcp_fixed_head 2 | 3 | import ( 4 | "os" 5 | "os/signal" 6 | "sync/atomic" 7 | "syscall" 8 | "time" 9 | 10 | "github.com/cclehui/server_on_gnet/commonutil" 11 | "github.com/panjf2000/ants/v2" 12 | "github.com/panjf2000/gnet/v2" 13 | "golang.org/x/net/context" 14 | ) 15 | 16 | func NewTCPFixHeadServer(port int) *TCPFixHeadServer { 17 | options := ants.Options{ExpiryDuration: time.Second * 10, Nonblocking: true} 18 | defaultAntsPool, _ := ants.NewPool(DefaultAntsPoolSize, ants.WithOptions(options)) 19 | 20 | server := &TCPFixHeadServer{} 21 | 22 | server.Port = port 23 | server.WorkerPool = defaultAntsPool 24 | server.Handler = defaultHandler 25 | server.ctx = context.Background() 26 | 27 | return server 28 | } 29 | 30 | // 启动服务 31 | func Run(server *TCPFixHeadServer, protoAddr string, opts ...gnet.Option) error { 32 | ctx := context.Background() 33 | 34 | go func() { 35 | // 监听系统信号量 36 | osSignal := make(chan os.Signal, 1) 37 | signal.Notify(osSignal, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT) 38 | 39 | for { 40 | select { 41 | case s := <-osSignal: 42 | commonutil.GetLogger().Infof(ctx, "收到系统信号:%s", s.String()) 43 | switch s { 44 | case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT, 45 | syscall.SIGHUP: 46 | err := gnet.Stop(ctx, protoAddr) 47 | if err != nil { 48 | commonutil.GetLogger().Errorf(ctx, "Stop error:%+v", err) 49 | } 50 | 51 | return 52 | default: 53 | } 54 | } 55 | } 56 | }() 57 | 58 | return gnet.Run(server, protoAddr, opts...) 59 | } 60 | 61 | type TCPFixHeadServer struct { 62 | Port int 63 | WorkerPool *ants.Pool 64 | 65 | ConnNum int32 66 | 67 | Handler ServerHandler 68 | 69 | ctx context.Context 70 | } 71 | 72 | func (tcphs *TCPFixHeadServer) OnBoot(eng gnet.Engine) (action gnet.Action) { 73 | commonutil.GetLogger().Infof(tcphs.ctx, "server started.....") 74 | return 75 | } 76 | 77 | func (tcphs *TCPFixHeadServer) OnShutdown(eng gnet.Engine) { 78 | commonutil.GetLogger().Infof(tcphs.ctx, "server shutdown...... ") 79 | } 80 | 81 | func (tcphs *TCPFixHeadServer) OnOpen(c gnet.Conn) (out []byte, action gnet.Action) { 82 | totalNum := atomic.AddInt32(&tcphs.ConnNum, 1) 83 | commonutil.GetLogger().Infof(tcphs.ctx, 84 | "total connection:%d, new connection: %s", totalNum, c.RemoteAddr()) 85 | 86 | return 87 | } 88 | 89 | func (tcphs *TCPFixHeadServer) OnClose(c gnet.Conn, err error) (action gnet.Action) { 90 | atomic.AddInt32(&tcphs.ConnNum, -1) 91 | commonutil.GetLogger().Debugf(tcphs.ctx, "close connection: %s", c.RemoteAddr()) 92 | 93 | return 94 | } 95 | 96 | func (tcphs *TCPFixHeadServer) OnTick() (delay time.Duration, action gnet.Action) { 97 | return 98 | } 99 | 100 | // 在 reactor 协程中做解码操作 101 | func (tcphs *TCPFixHeadServer) OnTraffic(c gnet.Conn) (action gnet.Action) { 102 | protocol := NewTCPFixHeadProtocol() 103 | 104 | protocolData, err := protocol.Decode(c) 105 | 106 | if err != nil { 107 | if err == ErrIncompletePacket { 108 | return gnet.None 109 | } 110 | commonutil.GetLogger().Errorf(tcphs.ctx, "Protocol Decode error :%+v\n", err) 111 | 112 | return gnet.Close // 关闭连接 113 | } 114 | 115 | if protocolData == nil { 116 | return gnet.None 117 | } 118 | 119 | // 具体业务在 worker pool中处理 120 | tcphs.WorkerPool.Submit(func() { 121 | handlerData := &HandlerContext{} 122 | handlerData.ProtocolData = protocolData 123 | handlerData.Conn = c 124 | handlerData.server = tcphs 125 | 126 | tcphs.Handler(handlerData) 127 | }) 128 | return 129 | } 130 | -------------------------------------------------------------------------------- /websocket/client.go: -------------------------------------------------------------------------------- 1 | package websocket 2 | 3 | import "html/template" 4 | 5 | var ClientTemplate = template.Must(template.New("").Parse(` 6 | 7 | 8 |
9 | 10 | 57 | 58 | 59 |
61 | Click "Open" to create a connection to the server, 62 | "Send" to send a message to the server and "Close" to close the connection. 63 | You can change the message and send multiple times. 64 | 65 | 71 | | 72 | 73 | |