为什么`go.net/websocket` API不使用通道来发送和接收消息呢?

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

Why does not go.net/websocket'api use channels for sending and receiving messages?

问题

go.net/websocket包中有Read()Write()函数,用于通过Web套接字发送和接收消息。为什么它不返回一个用于发送和接收消息的通道呢?我觉得像websocketnet这样的包是使用Go语言通道的理想场所。这个设计决策背后的原因是什么?

英文:

go.net/websocket package has Read() and Write() functions for sending and receiving messages through the web socket. Why does not it instead return a channel for sending and receiving messages? I feel like packages such as websocket, net are perfect places to use go's channels. What is the reasoning behind this design decision?

答案1

得分: 2

我不知道WebSockets的确切语义,但一般来说,我认为网络套接字不太适合映射到通道。实际上,曾经有一个叫做netchan的包试图使用通道来实现这个功能,但后来被停用了。

我认为使用一个通道实现来支持大量协议会有很多问题。消息从哪里开始,到哪里结束?通道应该缓冲大型消息,还是逐块传输?每个协议的语义差异太大,所以Go语言为套接字提供了更底层的读写操作,就像其他语言中的套接字一样,让你自己决定如何处理数据。

需要注意的是,我在谈论通常的套接字通道。WebSocket是一个定义明确的协议,使用通道的实现可能很适合它。至于为什么没有选择通道,最好向go.net/websocket的作者询问(可以尝试golang-nuts谷歌群组)。我认为从某种意义上讲,这是有道理的,因为现在的API与常规的Go套接字API相似。

需要注意的是,不使用通道并不意味着API不支持并发。只要连接在单独的goroutine中处理(在Go的HTTP服务器中是这样的),它们就会被并发处理。在这里,使用通道与否只是一种方便的方式。

英文:

I don't know the exact semantics of WebSockets, but in general, I don't think network sockets map well into channels. There was actually a netchan package that tried to did this with channels in general, but it was discontinued.

I think there many problems to try and support a whole lot of protocols with one channel implementation. Where does the message begin and end? Should the channel buffer a large message, or give it chunk by chunk, etc.? The semantics of each protocol differ too much, so Go gives you the lower-level Read/Write for sockets, just like you'd find in other languages and leaves it for you to decide how to handle the data.

Note that I'm talking about socket-channels in general. WebSocket is a well-defined protocol and an implementation using channels might work well for it. As for why channels weren't chosen, it would be best to ask the authors of go.net/websocket (try golang-nuts Google group). I think it makes sense in a way, as its API as it is now is similar to the regular Go socket API.

Note that not using channels does not make the API non-concurrent. As long as connections are being handled on separate goroutines (which they are, with Go's HTTP server), they'll be handled concurrently. Using a channel or not is just a matter of convenience here.

huangapple
  • 本文由 发表于 2013年8月30日 16:36:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/18528442.html
匿名

发表评论

匿名网友

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

确定