Golang RPC Simple Example

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

RPC (remote Procedure call Protocol)-a remoting protocol that requests services from a remote computer program over a network without needing to know the underlying network technology.

Its work flow is as follows:

Examples of Golang using RPC are as follows:

Server-side code:

This exposes an RPC interface, an HTTP interface

Package Main

Import (
"FMT"
"IO"
"NET"
"Net/http"
"Net/rpc"
)

Type Watcher int

Func (w *watcher) GetInfo (arg int, result *int) error {
*result = 1
return Nil
}

Func Main () {

http. Handlefunc ("/ghj1976", Ghj1976test)

Watcher: = new (Watcher)
Rpc. Register (Watcher)
Rpc. Handlehttp ()

L, Err: = Net. Listen ("TCP", ": 1234")
If err! = Nil {
Fmt. PRINTLN ("Listener failed, port may already be occupied")
}
Fmt. Println ("Listening on port 1234")
http. Serve (l, Nil)
}

Func ghj1976test (w http. Responsewriter, R *http. Request) {
Io. WriteString (W, "}

Client code:

Package Main

Import (
"FMT"
"Net/rpc"
)

Func Main () {
Client, err: = RPC. Dialhttp ("TCP", "127.0.0.1:1234")
If err! = Nil {
Fmt. Println ("Link RPC Server failed:", err)
}
var reply int
Err = client. Call ("Watcher.getinfo", 1, &reply)
If err! = Nil {
Fmt. PRINTLN ("Call remote service failed", err)
}
Fmt. PRINTLN ("Remote service Returns results:", reply)
}

Server-side code execution

Client code Execution

HTTP Web page Execution:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.