forked from madari/go-socket.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transport_websocket.go
109 lines (88 loc) · 2.44 KB
/
transport_websocket.go
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package socketio
import (
"http"
"os"
"websocket"
)
var errWebsocketHandshake = os.NewError("websocket handshake error")
// The websocket transport.
type websocketTransport struct {
rtimeout int64 // The period during which the client must send a message.
wtimeout int64 // The period during which a write must succeed.
}
// Creates a new websocket transport with the given read and write timeouts.
func NewWebsocketTransport(rtimeout, wtimeout int64) Transport {
return &websocketTransport{rtimeout, wtimeout}
}
// Returns the resource name.
func (t *websocketTransport) Resource() string {
return "websocket"
}
// Creates a new socket that can be used with a connection.
func (t *websocketTransport) newSocket() socket {
return &websocketSocket{t: t}
}
// websocketTransport implements the transport interface for websockets
type websocketSocket struct {
t *websocketTransport // the transport configuration
ws *websocket.Conn // the websocket connection
connected bool // used internally to represent the connection state
close chan byte
}
// Transport returns the transport the socket is based on.
func (s *websocketSocket) Transport() Transport {
return s.t
}
// String returns the verbose representation of the socket.
func (s *websocketSocket) String() string {
return s.t.Resource()
}
// Accepts a http connection & request pair. It upgrades the connection and calls
// proceed if succesfull.
//
// TODO: Remove the ugly channels and timeouts. They should not be needed!
func (s *websocketSocket) accept(w http.ResponseWriter, req *http.Request, proceed func()) (err os.Error) {
if s.connected {
return ErrConnected
}
f := func(ws *websocket.Conn) {
err = nil
ws.SetReadTimeout(s.t.rtimeout)
ws.SetWriteTimeout(s.t.wtimeout)
s.connected = true
s.ws = ws
s.close = make(chan byte)
defer close(s.close)
proceed()
// must block until closed
<-s.close
}
err = errWebsocketHandshake
websocket.Handler(f).ServeHTTP(w, req)
return
}
func (s *websocketSocket) Read(p []byte) (int, os.Error) {
if !s.connected {
return 0, ErrNotConnected
}
return s.ws.Read(p)
}
func (s *websocketSocket) Write(p []byte) (int, os.Error) {
if !s.connected {
return 0, ErrNotConnected
}
return s.ws.Write(p)
}
func (s *websocketSocket) Close() os.Error {
if !s.connected {
return ErrNotConnected
}
s.connected = false
go func() {
select {
case s.close <- 1:
default:
}
}()
return s.ws.Close()
}