當前位置: 首頁>>代碼示例>>Golang>>正文


Golang websocket.Dialer類代碼示例

本文整理匯總了Golang中github.com/gorilla/websocket.Dialer的典型用法代碼示例。如果您正苦於以下問題:Golang Dialer類的具體用法?Golang Dialer怎麽用?Golang Dialer使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了Dialer類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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


注:本文中的github.com/gorilla/websocket.Dialer類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。