網(wǎng)絡編程主要的內(nèi)容是:
1.TCP網(wǎng)絡編程
2.http服務
3.rpc服務
4.websocket服務
?
一、rpc
RPC 框架----- 遠程過程調(diào)用協(xié)議RPC(Remote Procedure Call Protocol)-----允許像調(diào)用本地服務一樣調(diào)用遠程服務。
RPC是指遠程過程調(diào)用,也就是說兩臺服務器A,B,一個應用部署在A服務器上,想要調(diào)用B服務器上應用提供的函數(shù)/方法,由于不在一個內(nèi)存空間,不能直接調(diào)用,需要通過網(wǎng)絡來表達調(diào)用的語義和傳達調(diào)用的數(shù)據(jù)
?1.1服務端,提供簡單的兩個數(shù)加法運算
package main
import (
"fmt"
"net"
"net/http"
"net/rpc"
)
type Server struct {
}
// 一樣的請求和響應結(jié)構(gòu)體
type Req struct {
Num1 int
Num2 int
}
type Res struct {
Num int
}
// 計算兩個數(shù)的和
func (s Server) Add(req Req, res *Res) error {
res.Num = req.Num1 + req.Num2
return nil
}
func main() {
//1.注冊rpc服務
rpc.Register(new(Server))
//2.綁定
rpc.HandleHTTP()
listen, err := net.Listen("tcp", ":8080")
if err != nil {
fmt.Println(err)
return
}
fmt.Println("服務已經(jīng)啟動...")
http.Serve(listen, nil)
}
1.2客戶端,調(diào)用服務端的函數(shù)
package main
import (
"fmt"
"net/rpc"
)
//與服務端一樣的請求和響應結(jié)構(gòu)體
type Req struct {
Num1 int
Num2 int
}
type Res struct {
Num int
}
func main() {
cleint, err := rpc.DialHTTP("tcp", ":8080")
if err != nil {
fmt.Println(err)
return
}
req := Req{1, 2}
var res Res
cleint.Call("Server.Add", req, &res)
fmt.Println(res)
}
代碼結(jié)構(gòu):
文章來源:http://www.zghlxwxcb.cn/news/detail-597869.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-597869.html
到了這里,關(guān)于golang網(wǎng)絡編程學習-1rpc的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!