goroute应用-模拟远程调用RPC

go语言简单模拟RPC,详见个人新博客:blog.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)
	}
}

  

上一篇:go编程的基本了解


下一篇:【Go】Golang Channel介绍