Server
package main
import (
"fmt"
"github.com/pkg/errors"
"log"
"net"
"net/rpc"
"net/rpc/jsonrpc"
"os"
)
type Arith struct {
}
type ArithRequest struct {
A int
B int
}
type ArithResponse struct {
Pro int
Que int
Rem int
}
func (this *Arith) Multiply(req ArithRequest, res *ArithResponse) error {
res.Pro = req.A * req.B
return nil
}
func (this *Arith) Divide(req ArithRequest, res *ArithResponse) error {
if req.B == 0 {
return errors.New("divide by zero")
}
res.Que = req.A / req.B
res.Rem = req.A % req.B
return nil
}
func (this *Arith) Add(a int, b *int) error {
*b = a + 5
return nil
}
func main() {
rpc.Register(new(Arith))
lis, err := net.Listen("tcp", "127.0.0.1:8096")
if err != nil {
log.Fatalln("fatal error: ", err)
}
fmt.Fprintf(os.Stdout, "%s", "start connection\n")
for {
conn, err := lis.Accept()
if err != nil {
fmt.Fprintf(os.Stdout, "%s", err)
continue
}
go func(conn net.Conn) {
fmt.Fprintf(os.Stdout, "%s", "new client in coming\n")
jsonrpc.ServeConn(conn)
}(conn)
}
}
client-go
package main
import (
"fmt"
"log"
"net/rpc/jsonrpc"
)
type ArithRequest struct {
A int
B int
}
type ArithResponse struct {
Pro int
Que int
Rem int
}
func main() {
conn, err := jsonrpc.Dial("tcp", "127.0.0.1:8096")
if err != nil{
log.Fatalln("dailing error: ", err)
}
req := ArithRequest{9,2}
var res ArithResponse
err = conn.Call("Arith.Multiply", req, &res)
if err != nil {
log.Fatalln("arith error: ", err)
}
fmt.Printf("%d * %d = %d\n", req.A, req.B, res.Pro)
err = conn.Call("Arith.Divide", req, &res)
if err != nil {
log.Fatalln("arith error: ", err)
}
fmt.Printf("%d / %d, quo is %d, rem is %d\n", req.A, req.B, res.Que, res.Rem)
}
client-python
import json
import requests
import socket
host = "127.0.0.1"
port = 8096
addr = (host, port)
tcpCliSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
req = {"A":9, "B": 2}
def main():
add = {
"method": "Arith.Add",
"params": [71],
"id": 0
}
multiply = {
"method": "Arith.Multiply",
"params": [req],
"id": 1
}
divide = {
"method": "Arith.Divide",
"params": [req],
"id": 2
}
tcpCliSock.connect(addr)
tcpCliSock.send(json.dumps(add).encode())
data_add = tcpCliSock.recv(2048)
print(data_add.decode())
tcpCliSock.send(json.dumps(multiply).encode())
data_multiply = tcpCliSock.recv(2048)
print(data_multiply.decode())
tcpCliSock.send(json.dumps(divide).encode())
data_divide = tcpCliSock.recv(2048)
print(data_divide.decode())
if __name__ == "__main__":
main()
有疑问加站长微信联系(非本文作者)