Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 20th, 2012  |  syntax: None  |  size: 1.16 KB  |  hits: 7  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Is websocket Send/Receive thread-safe (go routine-safe)?
  2. package main
  3.  
  4. import (
  5.     "fmt"
  6.     "net/http"
  7.     "code.google.com/p/go.net/websocket"
  8. )
  9.  
  10. const queueSize = 20
  11.  
  12. type Input struct {
  13.     Cmd    string
  14. }
  15.  
  16. type Output struct {
  17.     Cmd    string
  18. }
  19.  
  20. func Handler(ws *websocket.Conn) {
  21.  
  22.     msgWrite := make(chan *Output, queueSize)
  23.     var in Input
  24.  
  25.     go writeHandler(ws, msgWrite)
  26.  
  27.     for {
  28.  
  29.         err := websocket.JSON.Receive(ws, &in)
  30.  
  31.         if err != nil {
  32.             fmt.Println(err)
  33.             break
  34.         } else {
  35.             msgWrite <- &Output{Cmd: "Thanks for your message: " + in.Cmd}
  36.         }
  37.     }
  38. }
  39.  
  40. func writeHandler(ws *websocket.Conn, out chan *Output) {
  41.     var d *Output
  42.     for {
  43.         select {
  44.         case d = <-out:
  45.             if err := websocket.JSON.Send(ws, &d); err != nil {
  46.                 fmt.Println(err.Error())
  47.             } else {
  48.                 fmt.Println("> ", d.Cmd)
  49.             }
  50.         }
  51.     }
  52. }
  53.  
  54. func main() {
  55.     http.Handle("/echo", websocket.Handler(Handler));
  56.     err := http.ListenAndServe(":1235", nil);
  57.     if err != nil {
  58.         panic("ListenAndServe: " + err.Error())
  59.     }
  60.     fmt.Println("Server running")
  61. }