Golang RPC http.Serve与rpc.ServeConn的区别(HTTP与原始连接)

huangapple go评论84阅读模式
英文:

Golang RPC http.Serve vs rpc.ServeConn (HTTP vs raw connection)

问题

Go的net/rpc库允许通过原始网络连接或HTTP在网络上公开对象。以下是HTTP示例:

arith := new(Arith)
rpc.Register(arith)
rpc.HandleHTTP()
l, e := net.Listen("tcp", ":1234")
if e != nil {
    log.Fatal("listen error:", e)
}
go http.Serve(l, nil)

以下是原始TCP网络连接示例:

arith := new(Arith)
rpc.Register(arith)
l, e := net.Listen("tcp", ":1234")
if e != nil {
    log.Fatal("listen error:", e)
}
go func() {
    for {
        conn, err := l.Accept()
        go rpc.ServeConn(conn)
    } 
}

要调用第一种类型的服务器,可以使用rpc.DialHTTP("tcp", "127.0.0.1:1234"),而对于第二种类型,可以使用rpc.Dial("tcp", "127.0.0.1:1234")

这两种方法有什么真正的区别?在运行HTTP服务器与运行“原始网络连接”服务器之间有什么优缺点?是否可以通过curl或浏览器以某种方式使用HTTP执行RPC?HTTP版本是否适用于跨语言的RPC调用?

英文:

The Go net/rpc library documentation enables exposing an object across a network, either via raw network connections or via HTTP.

HTTP Example

arith := new(Arith)
rpc.Register(arith)
rpc.HandleHTTP()
l, e := net.Listen("tcp", ":1234")
if e != nil {
    log.Fatal("listen error:", e)
}
go http.Serve(l, nil)

Raw TCP Network Connection

arith := new(Arith)
rpc.Register(arith)
l, e := net.Listen("tcp", ":1234")
if e != nil {
    log.Fatal("listen error:", e)
}
go func() {
    for {
        conn, err := l.Accept()
        go rpc.ServeConn(conn)
    } 
}

To call the first type of server, one would use rpc.DialHTTP("tcp", "127.0.0.1:1234") and for the second type rpc.Dial("tcp", "127.0.0.1:1234") would be used.

My question is how are these two really different? What pros/cons are there to running an HTTP server vs. a "raw network connection" server? Can one perform RPCs via curl or the browser in some way with HTTP? Is the HTTP version useful for cross-language RPC invocation?

答案1

得分: 10

这个问题有一个很好的描述,介绍了HTTP和原始TCP之间的一般区别(与Go语言无关)。

https://stackoverflow.com/questions/1196623/tcp-vs-http-benchmark

基本上,它说HTTP是建立在TCP之上的一层标准化协议,如果你的代码需要在网页上发送请求并处理响应,那么你应该使用HTTP。但是,如果你只关心速度,可以不使用HTTP,而选择原始的TCP。

英文:

This question has an answer with a good description about the differences between HTTP and raw TCP in general (not directly concerning Go).

https://stackoverflow.com/questions/1196623/tcp-vs-http-benchmark

It basically says that since HTTP is a layer on top of TCP for standardization, it is something you should probably use if you plan on having your code having a webpage trying to make requests and processing the response, but if all you care about is speed, leave the HTTP off and go with raw TCP.

huangapple
  • 本文由 发表于 2013年10月29日 00:23:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/19640005.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定