首頁 >後端開發 >Golang >啟動套接字伺服器會幹擾 gRPC/http 用戶端伺服器通訊 Golang

啟動套接字伺服器會幹擾 gRPC/http 用戶端伺服器通訊 Golang

PHPz
PHPz轉載
2024-02-05 23:30:071284瀏覽

启动套接字服务器会干扰 gRPC/http 客户端服务器通信 Golang

問題內容

我有一個很大程度上是基於本教學的伺服器。在我對其應用了額外的更改後,它工作得很好。但現在我嘗試向其中添加 socket.io ,它現在遇到了一些問題。在測試我新增的 socket.io 程式碼後,它似乎影響了客戶端程式碼(端點)呼叫伺服器端程式碼(資料庫查詢、處理)的機制。當端點呼叫的日誌出現在終端機上時,呼叫到達伺服器的客戶端,但它似乎並未呼叫伺服器端。

這是套接字伺服器的程式碼:

package helpers

import (
    "fmt"
    "net/http"

    socketio "github.com/googollee/go-socket.io"
    "github.com/googollee/go-socket.io/engineio"
    "github.com/googollee/go-socket.io/engineio/transport"
    "github.com/googollee/go-socket.io/engineio/transport/polling"
    "github.com/googollee/go-socket.io/engineio/transport/websocket"
)

var alloworiginfunc = func(r *http.request) bool {
    return true
}

func startsocket() {
    server := socketio.newserver(&engineio.options{
        transports: []transport.transport{
            &polling.transport{
                checkorigin: alloworiginfunc,
            },
            &websocket.transport{
                checkorigin: alloworiginfunc,
            },
        },
    })

    server.onconnect("/", func(s socketio.conn) error {
        s.setcontext("")
        fmt.println("connected:", s.id())
        return nil
    })

    server.onevent("/", "notice", func(s socketio.conn, msg string) {
        fmt.println("notice:", msg)
        s.emit("reply", "have "+msg)
    })

    server.onerror("/", func(s socketio.conn, e error) {
        fmt.println("socket error:", e)
    })

    server.ondisconnect("/", func(s socketio.conn, reason string) {
        fmt.println("closed", reason)
    })

    go server.serve()
    defer server.close()

    http.handle("/socket.io/", server)
    http.handle("/", http.fileserver(http.dir("./asset")))

    fmt.println("socket server serving at localhost:8000...")
    fmt.print(http.listenandserve(":8000", nil))
}

// main.go 伺服器端

package main

import (
    "flag"
    "fmt"
    "log"
    "net"

    pb "github.com/<me>/<project_name>/api/proto/out"
    "github.com/<me>/<project_name>/cmd/server/handlers"
    "github.com/<me>/<project_name>/cmd/server/helpers"

    "google.golang.org/grpc"
    "google.golang.org/grpc/credentials"
)

func init() {
    helpers.databaseconnection()
}

var (
    tls      = flag.bool("tls", true, "connection uses tls if true, else plain tcp")
    certfile = flag.string("cert_file", "", "the tls cert file")
    keyfile  = flag.string("key_file", "", "the tls key file")
    port     = flag.int("port", 50051, "the server port")
)

func main() {
    flag.parse()

    // helpers.startsocket()

    lis, err := net.listen("tcp", fmt.sprintf("localhost:%d", *port))
    if err != nil {
        log.fatalf("failed to listen: %v", err)
    }

    var opts []grpc.serveroption
    if *tls {
        if *certfile == "" {
            *certfile = "service.pem"
        }

        if *keyfile == "" {
            *keyfile = "service.key"
        }

        creds, err := credentials.newservertlsfromfile(*certfile, *keyfile)

        if err != nil {
            log.fatalf("failed to generate credentials: %v", err)
        }

        opts = []grpc.serveroption{grpc.creds(creds)}
    }

    mserv := grpc.newserver(opts...)

    fmt.println("grpc server running ...")

    pb.registersomethingserviceserver(mserv, &handlers.somethingserver{})

    log.printf("server listening at %v", lis.addr())
    
    if err := mserv.serve(lis); err != nil {
        log.fatalf("failed to serve : %v", err)
    }
}

// main.go 客戶端

package main

import (
    "bytes"
    "encoding/json"
    "flag"
    "fmt"
    "log"
    "sort"
    "strings"

    "github.com/<me>/<project_name>/cmd/client/handlers"

    "github.com/gin-gonic/gin"
    "google.golang.org/grpc"
    "google.golang.org/grpc/credentials"
)

var (
    addr = flag.string("addr", "localhost:50051", "the address to connect to")
)

func main() {
    flag.parse()

    creds, err := credentials.newclienttlsfromfile("service.pem", "")

    if err != nil {
        log.fatalf("could not process the credentials: %v", err)
    }

    conn, err := grpc.dial(*addr, grpc.withtransportcredentials(creds))

    if err != nil {
        log.fatalf("did not connect: %v", err)
    }

    defer conn.close()

    var gingine = gin.default()
    startclient(conn, gingine)
}

func startclient(conn *grpc.clientconn, gingine *gin.engine) {

    handlers.somethingapihandler(conn, gingine)

    gingine.run(":5000")
}

有關完整的客戶端和伺服器程式碼,您可以查看我上面連結的教學。如果我不呼叫 startsocket(),一切正常。

當呼叫 api 的端點時,我收到此錯誤,該錯誤是由呼叫伺服器端程式碼的程式碼引發的:

"rpc error: code = unavailable desc = connection error: desc =
"transport: error while dialing: dial tcp [::1]:50051: connectex: no
connection could be made because the target machine actively refused
it.""

程式碼如下:

ginGine.POST("/account/login", func(ctx *gin.Context) {
    var account models.Account

    err := ctx.ShouldBind(&account)
    if err != nil {
        ctx.JSON(http.StatusBadRequest, gin.H{
            "error1": err.Error(),
        })
        return
    }

    res, err := srvClient.service.ValidateAccount(ctx, &pb.ValidateAccountRequest{
        Account: &pb.Account{
            Id:        account.ID,
            FirstName: account.FirstName,
            LastName:  account.LastName,
            UserName:  account.UserName,
            Password: account.Password,
        },
    })

    if err != nil {
        ctx.JSON(http.StatusBadRequest, gin.H{
            "error2": err.Error(),
        })
        return
    }

    ctx.JSON(http.StatusOK, gin.H{
        "status":       res.Status,
        "access_token": res.AccessToken,
    })
})

error2 是api 呼叫傳回的內容


正確答案


#這行程式碼是阻塞的,函數StartSocket() 永遠不會返回:

fmt.Print(http.ListenAndServe(":8000", nil))

為了測試,您可以在其後面新增日誌,並且該日誌訊息將不會列印。

您需要在單獨的非阻塞 goroutine 中執行 StartSocket()

附註例如,該行是 log.Fatal(http.ListenAndServe(":8000", nil))。您的程式碼吞下了一個錯誤。

以上是啟動套接字伺服器會幹擾 gRPC/http 用戶端伺服器通訊 Golang的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除