本文整理汇总了Golang中github.com/gorilla/websocket.Dialer类的典型用法代码示例。如果您正苦于以下问题:Golang Dialer类的具体用法?Golang Dialer怎么用?Golang Dialer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Dialer类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: getASocket
// getASocket calls MakeApiRequest() to get a websocket for the slack RTM
// interface.
func (b *Broker) getASocket() (*websocket.Conn, *ApiResponse, error) {
var req = ApiRequest{
URL: `https://slack.com/api/rtm.start`,
Values: make(url.Values),
Broker: b,
}
authResp, err := MakeAPIReq(req)
if err != nil {
return nil, nil, err
}
if authResp.URL == "" {
return nil, nil, fmt.Errorf("Auth failure")
}
wsURL := strings.Split(authResp.URL, "/")
wsURL[2] = wsURL[2] + ":443"
authResp.URL = strings.Join(wsURL, "/")
Logger.Debug(`Team Wesocket URL: `, authResp.URL)
var Dialer websocket.Dialer
header := make(http.Header)
header.Add("Origin", "http://localhost/")
ws, _, err := Dialer.Dial(authResp.URL, header)
if err != nil {
return nil, nil, fmt.Errorf("no dice dialing that websocket: %v", err)
}
//yay we're websocketing
return ws, authResp, nil
}
开发者ID:sharadgana,项目名称:lazlo,代码行数:33,代码来源:api.go
示例2: ServeHTTP
func (wp websocketProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
logger.Debug("Upgrading websocket connection.")
oconn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
logger.Error(err)
return
}
defer oconn.Close()
r.URL.Host = config.Destination
r.URL.Scheme = "ws"
dialer := websocket.Dialer{
HandshakeTimeout: time.Second,
ReadBufferSize: 1024,
WriteBufferSize: 1024,
Subprotocols: websocket.Subprotocols(r),
}
logger.Debug("Dialing", r.URL.String(), "...")
iconn, _, err := dialer.Dial(r.URL.String(), nil)
if err != nil {
logger.Error(err)
return
}
defer iconn.Close()
logger.Debug("Connected!")
go wp.Copy(oconn, iconn)
wp.Copy(iconn, oconn)
}
开发者ID:Victorystick,项目名称:authprox,代码行数:30,代码来源:websockets.go
示例3: Hijack
func (h *Hijacker) Hijack(handle string, spec atc.HijackProcessSpec, pio ProcessIO) (int, error) {
url, header, err := h.hijackRequestParts(handle)
if err != nil {
return -1, err
}
dialer := websocket.Dialer{
TLSClientConfig: h.tlsConfig,
Proxy: http.ProxyFromEnvironment,
}
conn, _, err := dialer.Dial(url, header)
if err != nil {
return -1, err
}
defer conn.Close()
err = conn.WriteJSON(spec)
if err != nil {
return -1, err
}
inputs := make(chan atc.HijackInput, 1)
finished := make(chan struct{}, 1)
go h.monitorTTYSize(inputs, finished)
go io.Copy(&stdinWriter{inputs}, pio.In)
go h.handleInput(conn, inputs, finished)
exitStatus := h.handleOutput(conn, pio)
close(finished)
return exitStatus, nil
}
开发者ID:ArthurHlt,项目名称:fly,代码行数:35,代码来源:hijacker.go
示例4: dial
func dial() (*websocket.Conn, error) {
LoadAuth()
if os.Getenv("TUTUM_STREAM_HOST") != "" {
u, _ := url.Parse(os.Getenv("TUTUM_STREAM_HOST"))
_, port, _ := net.SplitHostPort(u.Host)
if port == "" {
u.Host = u.Host + ":443"
}
StreamUrl = u.Scheme + "://" + u.Host + "/v1/"
} else if os.Getenv("TUTUM_STREAM_URL") != "" {
u, _ := url.Parse(os.Getenv("TUTUM_STREAM_URL"))
_, port, _ := net.SplitHostPort(u.Host)
if port == "" {
u.Host = u.Host + ":443"
}
StreamUrl = u.Scheme + "://" + u.Host + "/v1/"
}
Url := StreamUrl + "events/"
header := http.Header{}
header.Add("Authorization", AuthHeader)
header.Add("User-Agent", customUserAgent)
var Dialer websocket.Dialer
ws, _, err := Dialer.Dial(Url, header)
if err != nil {
return nil, err
}
return ws, nil
}
开发者ID:Karm,项目名称:go-tutum,代码行数:33,代码来源:stream.go
示例5: Logs
func (self *Service) Logs(c chan Logs) {
endpoint := ""
if Namespace != "" {
endpoint = "api/app/" + appSubsystemVersion + "/" + Namespace + "/service/" + self.Uuid + "/logs/"
} else {
endpoint = "api/app/" + appSubsystemVersion + "/service/" + self.Uuid + "/logs/"
}
url := StreamUrl + endpoint
header := http.Header{}
header.Add("Authorization", AuthHeader)
header.Add("User-Agent", customUserAgent)
var Dialer websocket.Dialer
ws, _, err := Dialer.Dial(url, header)
if err != nil {
log.Println(err)
}
var msg Logs
for {
if err = ws.ReadJSON(&msg); err != nil {
log.Println(err)
break
}
c <- msg
}
}
开发者ID:tamara32,项目名称:go-dockercloud,代码行数:30,代码来源:service.go
示例6: wsDial
func wsDial(src v2net.Address, dest v2net.Destination) (*wsconn, error) {
commonDial := func(network, addr string) (net.Conn, error) {
return internet.DialToDest(src, dest)
}
tlsconf := &tls.Config{ServerName: dest.Address().Domain(), InsecureSkipVerify: effectiveConfig.DeveloperInsecureSkipVerify}
dialer := websocket.Dialer{NetDial: commonDial, ReadBufferSize: 65536, WriteBufferSize: 65536, TLSClientConfig: tlsconf}
effpto := calcPto(dest)
uri := func(dst v2net.Destination, pto string, path string) string {
return fmt.Sprintf("%v://%v/%v", pto, dst.NetAddr(), path)
}(dest, effpto, effectiveConfig.Path)
conn, resp, err := dialer.Dial(uri, nil)
if err != nil {
if resp != nil {
reason, reasonerr := ioutil.ReadAll(resp.Body)
log.Info(string(reason), reasonerr)
}
return nil, err
}
return func() internet.Connection {
connv2ray := &wsconn{wsc: conn, connClosing: false}
connv2ray.setup()
return connv2ray
}().(*wsconn), nil
}
开发者ID:DZLZHCODE,项目名称:v2ray-core,代码行数:29,代码来源:dialer.go
示例7: ConnectToHead
func ConnectToHead(url string, secret string) {
var cstDialer = websocket.Dialer{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
conn, _, err := cstDialer.Dial(url, nil)
if err != nil {
fmt.Printf("Dial: %v", err)
}
log.Printf("ok")
// Send a welcome packet for auth
conn.WriteJSON(&common.Packet{
Cmd: "auth",
Context: secret,
})
for {
var p common.Packet
if err := conn.ReadJSON(&p); err != nil {
log.Println("Error reading head's json: ", err)
return
}
response := HandlePacket(p)
if response != nil {
conn.WriteJSON(response)
}
}
}
开发者ID:broluwo,项目名称:romaine-head,代码行数:34,代码来源:stem.go
示例8: startClient
func startClient(url *url.URL, wg *sync.WaitGroup, chRequests chan stats.MessageRequest,
chResponse chan *Response, id int) {
dialer := websocket.Dialer{}
conn, _, err := dialer.Dial(url.String(), nil)
if err != nil {
log.Fatal("Failed to establish connection with server: ", err)
}
defer conn.Close()
start := time.Now()
connected := true
var clientWg sync.WaitGroup
go func() {
for connected {
var mresp stats.MessageResponse
if err := conn.ReadJSON(&mresp); err != nil {
if connected {
log.Error("Error reading json response: ", err)
chResponse <- &Response{
Success: false,
}
clientWg.Done()
wg.Done()
}
} else {
log.Debug("Received response Host:", mresp.Host)
duration := time.Since(start)
chResponse <- &Response{
Success: true,
Duration: duration,
Valid: validateNodes(&mresp),
}
clientWg.Done()
wg.Done()
}
}
}()
for mreq := range chRequests {
clientWg.Add(1)
if err := conn.WriteJSON(&mreq); err != nil {
log.Error("Failed to send req: ", err)
clientWg.Done()
} else {
start = time.Now()
log.Debug("Sent req: ", mreq)
}
}
clientWg.Wait()
connected = false
}
开发者ID:mohabusama,项目名称:nodnod,代码行数:60,代码来源:nodnod_concurrent.go
示例9: Run
func (self *Container) Run(command string, c chan Exec) {
endpoint := "container/" + self.Uuid + "/exec/?user=" + User + "&token=" + ApiKey + "&command=" + url.QueryEscape(command)
url := StreamUrl + endpoint
header := http.Header{}
header.Add("User-Agent", customUserAgent)
var Dialer websocket.Dialer
ws, _, err := Dialer.Dial(url, header)
if err != nil {
log.Println(err)
}
var msg Exec
for {
if err = ws.ReadJSON(&msg); err != nil {
if err != nil && err.Error() != "EOF" {
log.Println(err)
} else {
break
}
}
c <- msg
}
}
开发者ID:Karm,项目名称:go-tutum,代码行数:26,代码来源:container.go
示例10: main
func main() {
// logger.SetConsole(true)
// logger.SetRollingDaily(".", "test.log")
// logger.SetLevel(logger.ALL)
flag.Parse()
var addr = flag.String("addr", "localhost:8080", "http service address")
var dialer = websocket.Dialer{}
u := url.URL{Scheme: "ws", Host: *addr, Path: "/gows"}
for {
errCh := make(chan error)
ws, _, err := dialer.Dial(u.String(), nil)
defer ws.Close()
if err == nil {
fmt.Println("runing")
go readMessages(ws, errCh)
go writeMessages(ws)
fmt.Println(<-errCh)
close(errCh)
}
if ws != nil {
ws.Close()
}
fmt.Println("reconning....")
time.Sleep(5 * time.Second)
}
}
开发者ID:fuqiang89,项目名称:WebSocketClient,代码行数:29,代码来源:main.go
示例11: newWebsocketPeer
func newWebsocketPeer(url, protocol, origin string, serializer Serializer, payloadType int) (Peer, error) {
dialer := websocket.Dialer{
Subprotocols: []string{protocol},
}
conn, _, err := dialer.Dial(url, nil)
if err != nil {
return nil, err
}
ep := &websocketPeer{
conn: conn,
messages: make(chan Message, 10),
serializer: serializer,
payloadType: payloadType,
}
go func() {
for {
// TODO: use conn.NextMessage() and stream
// TODO: do something different based on binary/text frames
if _, b, err := conn.ReadMessage(); err != nil {
conn.Close()
break
} else {
msg, err := serializer.Deserialize(b)
if err != nil {
// TODO: handle error
} else {
ep.messages <- msg
}
}
}
}()
return ep, nil
}
开发者ID:beatgammit,项目名称:turnpike,代码行数:33,代码来源:websocket.go
示例12: Logs
func (self *Container) Logs(c chan Logs) {
endpoint := "container/" + self.Uuid + "/logs/?user=" + User + "&token=" + ApiKey
url := StreamUrl + endpoint
header := http.Header{}
header.Add("User-Agent", customUserAgent)
var Dialer websocket.Dialer
ws, _, err := Dialer.Dial(url, header)
if err != nil {
log.Println(err)
}
var msg Logs
for {
if err = ws.ReadJSON(&msg); err != nil {
if err != nil && err.Error() != "EOF" {
log.Println(err)
} else {
break
}
}
c <- msg
}
}
开发者ID:Karm,项目名称:go-tutum,代码行数:26,代码来源:container.go
示例13: TestMainCLI
func TestMainCLI(t *testing.T) {
Convey("when I run the app", t, func() {
port := 9003
ctx, cancelFunc := context.WithCancel(context.Background())
app := MakeCliApp(ctx)
go app.Run([]string{"<executable path>", "--port", strconv.Itoa(port)})
time.Sleep(time.Millisecond)
url := fmt.Sprintf("ws://localhost:%v/", port)
d := websocket.Dialer{}
Convey("and connect", func() {
conn, _, err := d.Dial(url, http.Header{})
So(err, ShouldBeNil)
conn.Close()
})
Reset(func() {
cancelFunc()
time.Sleep(5 * time.Millisecond)
So("subicul", testutils.ShouldNotBeRunningGoroutines)
})
})
}
开发者ID:gitter-badger,项目名称:lucibus,代码行数:27,代码来源:cli_test.go
示例14: ConnectWebsocketSession
// ConnectWebsocketSession dials the remote specified in the opts and
// creates new websocket session.
func ConnectWebsocketSession(opts *DialOptions) (*WebsocketSession, error) {
dialURL, err := url.Parse(opts.BaseURL)
if err != nil {
return nil, err
}
// will be used to set the origin header
originalScheme := dialURL.Scheme
if err := replaceSchemeWithWS(dialURL); err != nil {
return nil, err
}
if err := addMissingPortAndSlash(dialURL); err != nil {
return nil, err
}
serverID := threeDigits()
sessionID := utils.RandomString(20)
// Add server_id and session_id to the path.
dialURL.Path += serverID + "/" + sessionID + "/websocket"
requestHeader := http.Header{}
requestHeader.Add("Origin", originalScheme+"://"+dialURL.Host)
ws := websocket.Dialer{
ReadBufferSize: opts.ReadBufferSize,
WriteBufferSize: opts.WriteBufferSize,
}
// if the user passed a custom HTTP client and its transport
// is of *http.Transport type - we're using its Dial field
// for connecting to remote host
if t, ok := opts.Client().Transport.(*http.Transport); ok {
ws.NetDial = t.Dial
}
// if the user passed a timeout, use a dial with a timeout
if opts.Timeout != 0 && ws.NetDial == nil {
// If ws.NetDial is non-nil then gorilla does not
// use ws.HandshakeTimeout for the deadlines.
//
// Instead we're going to set it ourselves.
ws.NetDial = (&net.Dialer{
Timeout: opts.Timeout,
Deadline: time.Now().Add(opts.Timeout),
}).Dial
}
conn, _, err := ws.Dial(dialURL.String(), requestHeader)
if err != nil {
return nil, err
}
session := NewWebsocketSession(conn)
session.id = sessionID
return session, nil
}
开发者ID:rjeczalik,项目名称:kite,代码行数:61,代码来源:sockjsclient.go
示例15: Connect
func Connect(address, user, pass string) (*websocket.Conn, *http.Response, error) {
authkey := base64.StdEncoding.EncodeToString([]byte(user + ":" + pass))
hdr := make(http.Header)
hdr.Add("Authorization", "Basic "+authkey)
var dialer websocket.Dialer
conn, resp, err := dialer.Dial("ws://"+address, hdr)
return conn, resp, err
}
开发者ID:algos,项目名称:kdb,代码行数:8,代码来源:kdb.go
示例16: connect
func (bot *Bot) connect(websocketURL string) (bool, error) {
dialer := websocket.Dialer{}
conn, _, err := dialer.Dial(websocketURL, http.Header{})
if err != nil {
return false, err
}
return bot.loop(conn), nil
}
开发者ID:ajm188,项目名称:slack,代码行数:8,代码来源:bot.go
示例17: WebsocketClient
func (a *Alphapoint) WebsocketClient() {
for a.ExchangeEnanbled && a.WebsocketEnabled {
var Dialer websocket.Dialer
var err error
a.WebsocketConn, _, err = Dialer.Dial(a.WebsocketURL, http.Header{})
if err != nil {
log.Printf("%s Unable to connect to Websocket. Error: %s\n", a.ExchangeName, err)
continue
}
if a.Verbose {
log.Printf("%s Connected to Websocket.\n", a.ExchangeName)
}
err = a.WebsocketConn.WriteMessage(websocket.TextMessage, []byte(`{"messageType": "logon"}`))
if err != nil {
log.Println(err)
return
}
for a.ExchangeEnanbled && a.WebsocketEnabled {
msgType, resp, err := a.WebsocketConn.ReadMessage()
if err != nil {
log.Println(err)
break
}
switch msgType {
case websocket.TextMessage:
type MsgType struct {
MessageType string `json:"messageType"`
}
msgType := MsgType{}
err := JSONDecode(resp, &msgType)
if err != nil {
log.Println(err)
continue
}
switch msgType.MessageType {
case "Ticker":
ticker := AlphapointWebsocketTicker{}
err = JSONDecode(resp, &ticker)
if err != nil {
log.Println(err)
continue
}
}
}
}
a.WebsocketConn.Close()
log.Printf("%s Websocket client disconnected.", a.ExchangeName)
}
}
开发者ID:jmaurice,项目名称:gocryptotrader,代码行数:57,代码来源:alphapointwebsocket.go
示例18: wsDial
func wsDial(src v2net.Address, dest v2net.Destination, options internet.DialerOptions) (*wsconn, error) {
networkSettings, err := options.Stream.GetEffectiveNetworkSettings()
if err != nil {
return nil, err
}
wsSettings := networkSettings.(*Config)
commonDial := func(network, addr string) (net.Conn, error) {
return internet.DialToDest(src, dest)
}
dialer := websocket.Dialer{
NetDial: commonDial,
ReadBufferSize: 65536,
WriteBufferSize: 65536,
}
protocol := "ws"
if options.Stream != nil && options.Stream.HasSecuritySettings() {
protocol = "wss"
securitySettings, err := options.Stream.GetEffectiveSecuritySettings()
if err != nil {
log.Error("WebSocket: Failed to create security settings: ", err)
return nil, err
}
tlsConfig, ok := securitySettings.(*v2tls.Config)
if ok {
dialer.TLSClientConfig = tlsConfig.GetTLSConfig()
if dest.Address.Family().IsDomain() {
dialer.TLSClientConfig.ServerName = dest.Address.Domain()
}
}
}
uri := func(dst v2net.Destination, pto string, path string) string {
return fmt.Sprintf("%v://%v/%v", pto, dst.NetAddr(), path)
}(dest, protocol, wsSettings.Path)
conn, resp, err := dialer.Dial(uri, nil)
if err != nil {
if resp != nil {
reason, reasonerr := ioutil.ReadAll(resp.Body)
log.Info(string(reason), reasonerr)
}
return nil, err
}
return func() internet.Connection {
connv2ray := &wsconn{
wsc: conn,
connClosing: false,
config: wsSettings,
}
connv2ray.setup()
return connv2ray
}().(*wsconn), nil
}
开发者ID:xyz12810,项目名称:v2ray-core,代码行数:57,代码来源:dialer.go
示例19: openWebSocket
func (start slackStart) openWebSocket() *websocket.Conn {
var emptyHeader http.Header
var defaultDialer *websocket.Dialer
conn, _, err := defaultDialer.Dial(start.URL, emptyHeader)
if err != nil {
panic(err)
}
return conn
}
开发者ID:adufrene,项目名称:gobot,代码行数:10,代码来源:gobot.go
示例20: WebsocketClient
func (b *Bitfinex) WebsocketClient() {
msgCounter := 0
for b.Enabled && b.Websocket {
var Dialer websocket.Dialer
var err error
b.WebsocketConn, _, err = Dialer.Dial(BITFINEX_WEBSOCKET, http.Header{})
if err != nil {
log.Printf("%s Unable to connect to Websocket. Error: %s\n", b.GetName(), err)
continue
}
if b.Verbose {
log.Printf("%s Connected to Websocket.\n", b.GetName())
}
err = b.Subscribe(&msgCounter, BITFINEX_WEBSOCKET_ORDERBOOK, map[string]interface{}{"ExchangeID": "0", "ProductPairID": "1", "Depth": 25, "RoundToDecimals": 2})
if err != nil {
log.Println(err)
continue
}
err = b.Subscribe(&msgCounter, BTIFINEX_WEBSOCKET_TRADES, map[string]interface{}{"ExchangeID": "0", "ProductPairID": "1", "IncludeLastCount": "100"})
if err != nil {
log.Println(err)
continue
}
if b.Verbose {
log.Printf("%s Subscribed to channels.\n", b.GetName())
}
for b.Enabled && b.Websocket {
msgType, resp, err := b.WebsocketConn.ReadMessage()
if err != nil {
log.Println(err)
break
}
switch msgType {
case websocket.TextMessage:
msg := BitfinexWebsocketResponse{}
err := JSONDecode(resp, &msg)
if err != nil {
log.Println(err)
continue
}
log.Println(string(resp))
log.Println(msg)
}
}
b.WebsocketConn.Close()
log.Printf("%s Websocket client disconnected.\n", b.GetName())
}
}
开发者ID:jmaurice,项目名称:gocryptotrader,代码行数:55,代码来源:bitfinexwebsocket.go
注:本文中的github.com/gorilla/websocket.Dialer类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论