Home > Software design >  Keeping connection for Golang net/rpc
Keeping connection for Golang net/rpc

Time:12-13

As I understand, reading net/rpc package documentation here https://pkg.go.dev/net/[email protected] that every time a client makes an rpc call to the server, a new connection established. How can achieve that each new client opens a new connection, keeps it alive and invokes RPC methods using only TPC, i.e. not using HTTP?

CodePudding user response:

If you make a new client with any of the standard library methods:

client, err := rpc.DialHTTP("tcp", serverAddress   ":1234")
if err != nil {
    log.Fatal("dialing:", err)
}

Underneath the hood it will call net.Dial, resulting in a single connection that is associated with the rpc.Client:

conn, err := net.Dial(network, address)

You can see NewClient taking a single connection when it's instantiated here: https://cs.opensource.google/go/go/ /refs/tags/go1.17.5:src/net/rpc/client.go;l=193-197;drc=refs/tags/go1.17.5;bpv=1;bpt=1

Any calls to Client.Call on that client will write and read to that underlying connection without spawning a new connection.

So as long as you instantiate your client one time and then make all of your rpc calls to that same client you'll always use a single connection. If that connection ever is severed the client will not longer be usable.

rpc.Client is also threadsafe, so you can safely create it and use it all over the place without having to make new connections .


Answering your comment. If you wanted to run an rpc server and keep track of connections you could do this:

l, e := net.Listen("tcp", ":1234")
if e != nil {
    log.Fatal("listen error:", e)
}
server := rpc.NewServer()
for {
    conn, err := l.Accept()
    if err != nil {
        panic(err) // replace with log message?
    }
    // Do something with `conn`
    go func() {
        server.ServeConn(conn)
        // The server has stopped serving this connection, you can remove it.
    }()
}

And then do something with each connection as it came in, and remove it when it's done processing.

  • Related