I am surprised that you did not receive an answer to this question.
What you need to do is something like the code below. When you receive an incoming connection to the network, a new goroutine is created for this connection. If you release this goroutine, it will disconnect the websocket client.
I make the assumption that you will not necessarily run the client and server on the same computer. If you always do this, then it would be better to do intercom via channels or such, instead of using web ports or a network port. I only mention this because I'm not quite sure what you are using it for. I just hope I answered the right part of your question.
package main import ( "code.google.com/p/go.net/websocket" "flag" "fmt" "net/http" "os" "time" ) type Message struct { RequestID int Command string SomeOtherThing string Success bool } var mode *string = flag.String("mode", "<nil>", "Mode: server or client") var address *string = flag.String("address", "localhost:8080", "Bind address:port") func main() { flag.Parse() switch *mode { case "server": RunServer() case "client": RunClient() default: flag.Usage() } } func RunServer() { http.Handle("/", http.FileServer(http.Dir("www"))) http.Handle("/server", websocket.Handler(WSHandler)) fmt.Println("Starting Server") err := http.ListenAndServe(*address, nil) if err != nil { fmt.Printf("HTTP failed: %s\n", err.Error()) os.Exit(1) } } func WSHandler(ws *websocket.Conn) { defer ws.Close() fmt.Println("Client Connected") for { var message Message err := websocket.JSON.Receive(ws, &message) if err != nil { fmt.Printf("Error: %s\n", err.Error()) return } fmt.Println(message) // do something useful here... response := new(Message) response.RequestID = message.RequestID response.Success = true response.SomeOtherThing = "The hot dog left the castle as requested." err = websocket.JSON.Send(ws, response) if err != nil { fmt.Printf("Send failed: %s\n", err.Error()) os.Exit(1) } } } func RunClient() { fmt.Println("Starting Client") ws, err := websocket.Dial(fmt.Sprintf("ws://%s/server", *address), "", fmt.Sprintf("http://%s/", *address)) if err != nil { fmt.Printf("Dial failed: %s\n", err.Error()) os.Exit(1) } incomingMessages := make(chan Message) go readClientMessages(ws, incomingMessages) i := 0 for { select { case <-time.After(time.Duration(2e9)): i++ response := new(Message) response.RequestID = i response.Command = "Eject the hot dog." err = websocket.JSON.Send(ws, response) if err != nil { fmt.Printf("Send failed: %s\n", err.Error()) os.Exit(1) } case message := <-incomingMessages: fmt.Println(message) } } } func readClientMessages(ws *websocket.Conn, incomingMessages chan Message) { for { var message Message err := websocket.JSON.Receive(ws, &message) if err != nil { fmt.Printf("Error: %s\n", err.Error()) return } incomingMessages <- message } }
source share