goroute应用-模拟远程调用RPC

go语言简单模拟RPC,详见个人新博客:www.dlgde.cn

代码如下:

package main

import (
	"errors"
	"fmt"
	"time"
)

func RPCClient(ch chan string, req string) (string, error) {
	ch <- req
	select {
	case ack := <-ch:
		return ack, nil
	case <-time.After(time.Second):
		return "", errors.New("Time out")
	}
}

func RPCServer(ch chan string) {
	for {
		data := <-ch
		fmt.Println("server received:", data)
		//time.Sleep(time.Second * 2)
		ch <- "roger"
	}

}

func main() {
	ch := make(chan string)
	go RPCServer(ch)

	recv, err := RPCClient(ch, "hi")

	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println("client received", recv)
	}
}

  

posted @ 2019-04-19 22:40  qstudy  阅读(209)  评论(0编辑  收藏  举报