rpc demo

2018-09-30  本文已影响0人  吃猫的鱼0

client

import (
    "fmt"
    "net/rpc"
)

func main() {
    fmt.Println("client====")
    client, err := rpc.DialHTTP("tcp", "127.0.0.1:1234")
    if err != nil {
        fmt.Println("链接rpc服务器失败:", err)
    }
    var reply int
    err = client.Call("Watcher.GetInfo", 1, &reply)
    if err != nil {
        fmt.Println("调用远程服务失败", err)
    }
    fmt.Println("远程服务返回结果:", reply)
}

server


import (
    "fmt"
    "io"
    "net"
    "net/http"
    "net/rpc"
    "sync"
)

type Watcher int

func (w *Watcher) GetInfo(arg int, result *int) error {
    *result = 1
    return nil
}

func main() {
    fmt.Println("server====")
    http.HandleFunc("/ghj1976", Ghj1976Test)

    watcher := new(Watcher)
    rpc.Register(watcher)
    rpc.HandleHTTP()

    l, err := net.Listen("tcp", ":1234")
    if err != nil {
        fmt.Println("监听失败,端口可能已经被占用")
    }
    fmt.Println("正在监听1234端口")
    http.Serve(l, nil)
}

func Ghj1976Test(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "<html><body>ghj1976-123</body></html>")
}

type chanMap struct {
    v map[string]chan []byte
    sync.RWMutex
}

// 更新
func (this *chanMap) Set(key string, value chan []byte) {
    this.Lock()
    defer this.Unlock()
    v, ok := this.v[key]
    if !ok {
        this.v[key] = value
    }
    v <- []byte("bad request")
    this.v[key] = value
}

// 查找
func (this *chanMap) Get(key string) (value chan []byte, ok bool) {
    this.RLock()
    defer this.RUnlock()
    value, ok = this.v[key]
    return
}

// 删除
func (this *chanMap) Del(key string) {
    this.Lock()
    defer this.Unlock()
    delete(this.v, key)
}

func wxTest(w http.ResponseWriter, r *http.Request) {
    masage := make(chan []byte, 1)
    // 中间处理的逻辑
    mass:=<-masage
    w.Write(mass)
}

上一篇下一篇

猜你喜欢

热点阅读