1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
14 func newServerConn(rwc io.ReadWriteCloser, buf *bufio.ReadWriter, req *http.Request) (conn *Conn, err error) {
16 var hs serverHandshaker = &hybiServerHandshaker{Config: config}
17 code, err := hs.ReadHandshake(buf.Reader, req)
18 if err == ErrBadWebSocketVersion {
19 fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
20 fmt.Fprintf(buf, "Sec-WebSocket-Version: %s\r\n", SupportedProtocolVersion)
21 buf.WriteString("\r\n")
22 buf.WriteString(err.Error())
27 hs = &hixie76ServerHandshaker{Config: config}
28 code, err = hs.ReadHandshake(buf.Reader, req)
31 hs = &hixie75ServerHandshaker{Config: config}
32 code, err = hs.ReadHandshake(buf.Reader, req)
35 fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
36 buf.WriteString("\r\n")
37 buf.WriteString(err.Error())
43 err = hs.AcceptHandshake(buf.Writer)
45 code = http.StatusBadRequest
46 fmt.Fprintf(buf, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
47 buf.WriteString("\r\n")
51 conn = hs.NewServerConn(buf, rwc, req)
56 Handler is an interface to a WebSocket.
58 A trivial example server:
68 // Echo the data received on the WebSocket.
69 func EchoServer(ws *websocket.Conn) {
74 http.Handle("/echo", websocket.Handler(EchoServer));
75 err := http.ListenAndServe(":12345", nil);
77 panic("ListenAndServe: " + err.Error())
81 type Handler func(*Conn)
83 // ServeHTTP implements the http.Handler interface for a Web Socket
84 func (h Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
85 rwc, buf, err := w.(http.Hijacker).Hijack()
87 panic("Hijack failed: " + err.Error())
90 // The server should abort the WebSocket connection if it finds
91 // the client did not send a handshake that matches with protocol
94 conn, err := newServerConn(rwc, buf, req)
99 panic("unepxected nil conn")