How to carry out Go jsonrpc
Today, I would like to talk to you about how to carry out Go jsonrpc, many people may not know much about it. In order to make you understand better, the editor has summarized the following contents for you. I hope you can get something according to this article.
Hello, everyone. As I have been busy for a long time, I would like to introduce to you the following jsonrpc usage of go. I don't say much about the theoretical principle. I personally think it is best to understand the principle by looking at the comments of the code.
(1) Server code
Package main
Import (
"fmt"
"log"
"net"
"net/rpc"
"net/rpc/jsonrpc"
"os"
)
/ / Resp return value structure
Type Resp struct {
Country string
Province string
City string
Latitude float64
Longitude float64
TimeZone string
Data string
}
/ / Serve
Type Serve struct {
}
/ / Parameter structure
Type Agrs struct {
IpString string
Data string
}
/ / json rpc processes requests
/ / GetData acquires data
Func (s * Serve) GetData (agr Agrs, res * Resp) error {
Res.City = "Nanning"
Res.Province = "Guangxi"
Res.Country = "China"
Res.Latitude = 888.888
Res.Longitude = 111.111
Res.TimeZone = "ssss"
Res.Data = agr.Data / / return the data you sent
Return nil
}
Func main () {
/ / initialize jsonRPC
Serve: = & Serve {}
/ / Registration service
Rpc.Register (serve)
/ / bind port
Address: = "127.0.0.1 purl 8080"
TcpAddr, err: = net.ResolveTCPAddr ("tcp", address)
CheckError (err)
Listener, err: = net.ListenTCP ("tcp", tcpAddr)
CheckError (err)
Log.Println ("json rpc is listening", tcpAddr)
/ / always connect
For {
Conn, err: = listener.Accept ()
If err! = nil {
Continue
}
Go jsonrpc.ServeConn (conn)
}
}
/ / Verification error
Func checkError (err error) {
If err! = nil {
Fmt.Println ("Fatal error", err.Error ())
Os.Exit (1)
}
}
(2) client code
Package main
Import (
"fmt"
"log"
"net/rpc"
"net/rpc/jsonrpc"
)
Type Response struct {
Country string
Province string
City string
Latitude float64
Longitude float64
TimeZone string
Data string
}
Type Client struct {
* rpc.Client
}
Type agrs struct {
IpString string
Data string
}
Func main () {
Var (
C = new (Client)
Err error
)
If c.Client, err = jsonrpc.Dial ("tcp", "127.0.0.1 jsonrpc.Dial 8080"); err! = nil {
Log.Fatal ("dialing:", err)
}
/ / Synchronous call
Var res Response
Var an agrs
A.IpString = "219.140.227.235"
A.Data = "is my data"
Err = c.Call ("Serve.GetData", & a, & res)
If err! = nil {
Log.Fatal ("ip2addr error:", err)
}
Fmt.Println (res)
}
(3) run
Run server.go
Then run client.go
You'll have a surprise.
After reading the above, do you have any further understanding of how to carry out Go jsonrpc? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.