go websocket 关闭_Go实战--使用之gorilla/websocket
聲明不止,繼續 go go go!!!
關于websocket,不會陌生。
之前也有博客介紹過golang中使用websocket,其中介紹了兩個第三方庫:
gorilla/websocket
nkovacs/go-socket.io
Go實戰–golang中使用WebSocket實時聊天室(gorilla/websocket、nkovacs/go-socket.io)
所以,趁著介紹gorilla工具博客系列,今天就再重新介紹一下gorilla/websocket。
WebSocket
WebSocket是HTML5開始提供的一種瀏覽器與服務器間進行全雙工通訊的網絡技術。 WebSocket通信協議于2011年被IETF定為標準RFC 6455,WebSocketAPI被W3C定為標準。 在WebSocket API中,瀏覽器和服務器只需要要做一個握手的動作,然后,瀏覽器和服務器之間就形成了一條快速通道。兩者之間就直接可以數據互相傳送。
TCP: low-level, bi-directional, full-duplex, and guaranteed order transport layer. No browser support (except via plugin/Flash).
HTTP 1.0: request-response transport protocol layered on TCP. The client makes one full request, the server gives one full response, and then the connection is closed. The request methods (GET, POST, HEAD) have specific transactional meaning for resources on the server.
HTTP 1.1: maintains the request-response nature of HTTP 1.0, but allows the connection to stay open for multiple full requests/full responses (one response per request). Still has full headers in the request and response but the connection is re-used and not closed. HTTP 1.1 also added some additional request methods (OPTIONS, PUT, DELETE, TRACE, CONNECT) which also have specific transactional meanings. However, as noted in the introduction to the HTTP 2.0 draft proposal, HTTP 1.1 pipelining is not widely deployed so this greatly limits the utility of HTTP 1.1 to solve latency between browsers and servers.
Long-poll: sort of a “hack” to HTTP (either 1.0 or 1.1) where the server does not response immediately (or only responds partially with headers) to the client request. After a server response, the client immediately sends a new request (using the same connection if over HTTP 1.1).
HTTP streaming: a variety of techniques (multipart/chunked response) that allow the server to send more than one response to a single client request. The W3C is standardizing this as Server-Sent Events using a text/event-stream MIME type. The browser API (which is fairly similar to the WebSocket API) is called the EventSource API.
Comet/server push: this is an umbrella term that includes both long-poll and HTTP streaming. Comet libraries usually support multiple techniques to try and maximize cross-browser and cross-server support.
WebSockets: a transport layer built-on TCP that uses an HTTP friendly Upgrade handshake. Unlike TCP, which is a streaming transport, WebSockets is a message based transport: messages are delimited on the wire and are re-assembled in-full before delivery to the application. WebSocket connections are bi-directional, full-duplex and long-lived. After the initial handshake request/response, there is no transactional semantics and there is very little per message overhead. The client and server may send messages at any time and must handle message receipt asynchronously.
HTTP 2.0: has similar goals to SPDY: reduce HTTP latency and overhead while preserving HTTP semantics. The current draft is derived from SPDY and defines an upgrade handshake and data framing that is very similar the the WebSocket standard for handshake and framing. An alternate HTTP 2.0 draft proposal (httpbis-speed-mobility) actually uses WebSockets for the transport layer and adds the SPDY multiplexing and HTTP mapping as an WebSocket extension (WebSocket extensions are negotiated during the handshake).
WebRTC/CU-WebRTC: proposals to allow peer-to-peer connectivity between browsers. This may enable lower average and maximum latency communication because as the underlying transport is SDP/datagram rather than TCP. This allows out-of-order delivery of packets/messages which avoids the TCP issue of latency spikes caused by dropped packets which delay delivery of all subsequent packets (to guarantee in-order delivery).
特點:
(1)建立在 TCP 協議之上,服務器端的實現比較容易。
(2)與 HTTP 協議有著良好的兼容性。默認端口也是80和443,并且握手階段采用 HTTP 協議,因此握手時不容易屏蔽,能通過各種 HTTP 代理服務器。
(3)數據格式比較輕量,性能開銷小,通信高效。
(4)可以發送文本,也可以發送二進制數據。
(5)沒有同源限制,客戶端可以與任意服務器通信。
(6)協議標識符是ws(如果加密,則為wss),服務器網址就是 URL
gorilla/websocket
獲取:
go get github.com/gorilla/websocket
API:
官方例子:
https://github.com/gorilla/websocket/tree/master/examples/chat
HTML5 WebSocket
以下 API 用于創建 WebSocket 對象。
var Socket = new WebSocket(url, [protocol] );1事件
open Socket.onopen 連接建立時觸發
message Socket.onmessage 客戶端接收服務端數據時觸發
error Socket.onerror 通信發生錯誤時觸發
close Socket.onclose 連接關閉時觸發
例子:
菜鳥教程(runoob.com) 運行 WebSocket 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253簡單例子h5+golang
main.go
package mainimport ( "fmt" "io/ioutil" "net/http" "github.com/gorilla/websocket")type msg struct { Num int}func main() { http.HandleFunc("/ws", wsHandler) http.HandleFunc("/", rootHandler) panic(http.ListenAndServe(":8080", nil))}func rootHandler(w http.ResponseWriter, r *http.Request) { content, err := ioutil.ReadFile("index.html") if err != nil { fmt.Println("Could not open file.", err) } fmt.Fprintf(w, "%s", content)}func wsHandler(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Origin") != "http://"+r.Host { http.Error(w, "Origin not allowed", 403) return } conn, err := websocket.Upgrade(w, r, w.Header(), 1024, 1024) if err != nil { http.Error(w, "Could not open websocket connection", http.StatusBadRequest) } go echo(conn)}func echo(conn *websocket.Conn) { for { m := msg{} err := conn.ReadJSON(&m) if err != nil { fmt.Println("Error reading json.", err) } fmt.Printf("Got message: %#v", m) if err = conn.WriteJSON(m); err != nil { fmt.Println(err) } }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859index.html
WebSocket demo Number Send總結
以上是生活随笔為你收集整理的go websocket 关闭_Go实战--使用之gorilla/websocket的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: abaqus 多层网格绑定_ABAQUS
- 下一篇: 13号线ab线规划图_大连地铁2050路