Web sockets over TLS

A web socket can be built above a secure TLS socket. We discussed in Chapter 8: HTTP how to use a TLS socket using the certificates from Chapter 7: Security. That is used unchanged for web sockets. that is, we use http.ListenAndServeTLS instead of http.ListenAndServe.

Here is the echo server using TLS

  1. /* EchoServer
  2. */
  3. package main
  4. import (
  5. "golang.org/x/net/websocket"
  6. "fmt"
  7. "net/http"
  8. "os"
  9. )
  10. func Echo(ws *websocket.Conn) {
  11. fmt.Println("Echoing")
  12. for n := 0; n < 10; n++ {
  13. msg := "Hello " + string(n+48)
  14. fmt.Println("Sending to client: " + msg)
  15. err := websocket.Message.Send(ws, msg)
  16. if err != nil {
  17. fmt.Println("Can't send")
  18. break
  19. }
  20. var reply string
  21. err = websocket.Message.Receive(ws, &reply)
  22. if err != nil {
  23. fmt.Println("Can't receive")
  24. break
  25. }
  26. fmt.Println("Received back from client: " + reply)
  27. }
  28. }
  29. func main() {
  30. http.Handle("/", websocket.Handler(Echo))
  31. err := http.ListenAndServeTLS(":12345", "jan.newmarch.name.pem",
  32. "private.pem", nil)
  33. checkError(err)
  34. }
  35. func checkError(err error) {
  36. if err != nil {
  37. fmt.Println("Fatal error ", err.Error())
  38. os.Exit(1)
  39. }
  40. }

The client is the same echo client as before. All that changes is the url, which uses the "wss" scheme instead of the "ws" scheme:

  1. EchoClient wss://localhost:12345/

Conclusion

The web sockets standard is nearing completion and no major changes are anticipated. This will allow HTTP user agents and servers to set up bi-directional socket connections and should make certain interaction styles much easier. Go has nearly complete support for web sockets.