golang rpc demo

空扰寡人 提交于 2020-10-24 18:59:40

server.go

package main

import (
    "log"
    "net"
    "net/http"
    "net/rpc"
    "net/rpc/jsonrpc"
)

type Args struct {
    A int
    B int
}

type Number struct{}

// 方法参数列表必须为此格式
func (num *Number) Sum(args *Args, sum *int) error {
    *sum = args.A + args.B

    return nil
}

func TcpServer() {
    ln, err := net.Listen("tcp", "127.0.0.1:9008")
    if err != nil {
        log.Fatalln("net.Listen error:", err)
    }

    log.Println("start connection")

    for {
        // 接收客户端连接请求
        conn, err := ln.Accept()
        if err != nil {
            log.Println("ln.Accept error:", err)
            continue
        }

        // 处理客户端请求
        go func(conn net.Conn) {
            log.Println("new client in coming")
            jsonrpc.ServeConn(conn)
        }(conn)
    }
}

func HttpServer() {
    rpc.HandleHTTP()
    ln, err := net.Listen("tcp", "127.0.0.1:9009")
    if err != nil {
        log.Fatalln("net.Listen error:", err)
    }

    err = http.Serve(ln, nil)
    if err != nil {
        log.Fatalln("http.Serve error:", err)
    }
}

func main() {
    err := rpc.Register(&Number{})
    if err != nil {
        log.Fatalln("rpc.Register error:", err)
    }

    go TcpServer()
    go HttpServer()

    select {}
}

client.go

package main

import (
    "log"
    "net/rpc"
    "net/rpc/jsonrpc"
    "time"
)

type Args struct {
    A int
    B int
}

func Tcp() {
    client, err := jsonrpc.Dial("tcp", "127.0.0.1:9008")
    if err != nil {
        log.Fatalln("jsonrpc.Dial error:", err)
    }

    args := &Args{9, 2}
    var sum int

    // 调用方法
    err = client.Call("Number.Sum", args, &sum)
    if err != nil {
        log.Fatalln("conn.Call error:", err)
    }
    log.Println("Tcp result:", sum)
}

func Http() {
    client, err := rpc.DialHTTP("tcp", "127.0.0.1:9009")
    if err != nil {
        log.Fatalln("jsonrpc.Dial error:", err)
    }

    args := &Args{9, 2}
    var sum int

    // 调用方法
    err = client.Call("Number.Sum", args, &sum)
    if err != nil {
        log.Fatalln("conn.Call error:", err)
    }
    log.Println("Http result:", sum)
}

func Async() {
    client, err := jsonrpc.Dial("tcp", "127.0.0.1:9008")
    // client, err := rpc.DialHTTP("tcp", "127.0.0.1:9009")
    if err != nil {
        log.Fatalln("jsonrpc.Dial error:", err)
    }
    args := &Args{9, 2}
    var sum int

    call := client.Go("Number.Sum", args, &sum, nil)
    <-call.Done
    log.Println("Async result:", sum)
}

func main() {
    go Tcp()
    go Http()
    go Async()
    <-time.After(time.Second)
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!