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.
16 // DialError is an error that occurs while dialling a websocket server.
17 type DialError
struct {
22 func (e
*DialError
) String() string {
23 return "websocket.Dial " + e
.Config
.Location
.String() + ": " + e
.Error
.String()
26 // NewConfig creates a new WebSocket config for client connection.
27 func NewConfig(server
, origin
string) (config
*Config
, err os
.Error
) {
29 config
.Version
= ProtocolVersionHybi13
30 config
.Location
, err
= url
.ParseRequest(server
)
34 config
.Origin
, err
= url
.ParseRequest(origin
)
41 // NewClient creates a new WebSocket client connection over rwc.
42 func NewClient(config
*Config
, rwc io
.ReadWriteCloser
) (ws
*Conn
, err os
.Error
) {
43 br
:= bufio
.NewReader(rwc
)
44 bw
:= bufio
.NewWriter(rwc
)
45 switch config
.Version
{
46 case ProtocolVersionHixie75
:
47 err
= hixie75ClientHandshake(config
, br
, bw
)
48 case ProtocolVersionHixie76
, ProtocolVersionHybi00
:
49 err
= hixie76ClientHandshake(config
, br
, bw
)
50 case ProtocolVersionHybi08
, ProtocolVersionHybi13
:
51 err
= hybiClientHandshake(config
, br
, bw
)
53 err
= ErrBadProtocolVersion
58 buf
:= bufio
.NewReadWriter(br
, bw
)
59 switch config
.Version
{
60 case ProtocolVersionHixie75
, ProtocolVersionHixie76
, ProtocolVersionHybi00
:
61 ws
= newHixieClientConn(config
, buf
, rwc
)
62 case ProtocolVersionHybi08
, ProtocolVersionHybi13
:
63 ws
= newHybiClientConn(config
, buf
, rwc
)
69 Dial opens a new client connection to a WebSocket.
71 A trivial example client:
83 origin := "http://localhost/"
84 url := "ws://localhost/ws"
85 ws, err := websocket.Dial(url, "", origin)
89 if _, err := ws.Write([]byte("hello, world!\n")); err != nil {
92 var msg = make([]byte, 512);
93 if n, err := ws.Read(msg); err != nil {
99 func Dial(url_
, protocol
, origin
string) (ws
*Conn
, err os
.Error
) {
100 config
, err
:= NewConfig(url_
, origin
)
104 return DialConfig(config
)
107 // DialConfig opens a new client connection to a WebSocket with a config.
108 func DialConfig(config
*Config
) (ws
*Conn
, err os
.Error
) {
110 if config
.Location
== nil {
111 return nil, &DialError
{config
, ErrBadWebSocketLocation
}
113 if config
.Origin
== nil {
114 return nil, &DialError
{config
, ErrBadWebSocketOrigin
}
116 switch config
.Location
.Scheme
{
118 client
, err
= net
.Dial("tcp", config
.Location
.Host
)
121 client
, err
= tls
.Dial("tcp", config
.Location
.Host
, config
.TlsConfig
)
130 ws
, err
= NewClient(config
, client
)
137 return nil, &DialError
{config
, err
}