Gorilla Websockets, golang simple websockets example
I previously posted a quick example of using the standard library websockets API in golang. Unfortunately there are a number of issues that make difficult to use in practice. Notably, it lacks support for PING/PONG packets which are often used to for KeepAlive functionality in websockets. This is particularly important, as browsers tend to be aggressive in killing off these connections.
So, here’s a quick complete example of Gorilla Websockets in golang, with similar functionality to that I posted previously. It simply echos everything it receives back to the client. First the golang code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | package main import ( "github.com/gorilla/websocket" "net/http" "fmt" ) var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } func print_binary(s []byte) { fmt.Printf( "Received b:" ); for n := 0;n < len(s);n++ { fmt.Printf( "%d," ,s[n]); } fmt.Printf( "\n" ); } func echoHandler(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { //log.Println(err) return } for { messageType, p, err := conn.ReadMessage() if err != nil { return } print_binary(p) err = conn.WriteMessage(messageType, p); if err != nil { return } } } func main() { http.HandleFunc( "/echo" , echoHandler) http.Handle( "/" , http.FileServer(http.Dir( "." ))) err := http.ListenAndServe( ":8080" , nil) if err != nil { panic( "Error: " + err.Error()) } } |
And then the html used to interface with the websocket. Save it in the same directory as the golang program, and access it at: http://localhost:8080/filename.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | < html > < head > < meta charset = "UTF-8" /> < script > var serversocket = new WebSocket("ws://localhost:8080/echo"); serversocket.onopen = function() { serversocket.send("Connection init"); } // Write message on receive serversocket.onmessage = function(e) { document.getElementById('comms').innerHTML += "Received: " + e.data + "< br >"; }; function senddata() { var data = document.getElementById('sendtext').value; serversocket.send(data); document.getElementById('comms').innerHTML += "Sent: " + data + "< br >"; } </ script > </ head > < body > < input id = "sendtext" type = "text" /> < input type = "button" id = "sendBtn" value = "send" onclick = "senddata()" ></ input > < div id = 'comms' ></ div > </ body > </ html > |