コード例 #1
2
ファイル: api.go プロジェクト: sharadgana/lazlo
// 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
}
コード例 #2
0
ファイル: websockets.go プロジェクト: Victorystick/authprox
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)

}
コード例 #3
0
ファイル: hijacker.go プロジェクト: ArthurHlt/fly
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
}
コード例 #4
0
ファイル: stream.go プロジェクト: Karm/go-tutum
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
}
コード例 #5
0
ファイル: service.go プロジェクト: tamara32/go-dockercloud
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
	}
}
コード例 #6
0
ファイル: dialer.go プロジェクト: DZLZHCODE/v2ray-core
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
}
コード例 #7
0
ファイル: stem.go プロジェクト: broluwo/romaine-head
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)
		}
	}
}
コード例 #8
0
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
}
コード例 #9
0
ファイル: container.go プロジェクト: Karm/go-tutum
func (self *Container) Run(command string, c chan Exec) {

	endpoint := "container/" + self.Uuid + "/exec/?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
	}
}
コード例 #10
0
ファイル: main.go プロジェクト: fuqiang89/WebSocketClient
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)
	}
}
コード例 #11
0
ファイル: websocket.go プロジェクト: beatgammit/turnpike
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
}
コード例 #12
0
ファイル: container.go プロジェクト: Karm/go-tutum
func (self *Container) Logs(c chan Logs) {

	endpoint := "container/" + self.Uuid + "/logs/?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
	}
}
コード例 #13
0
ファイル: cli_test.go プロジェクト: gitter-badger/lucibus
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)
		})

	})

}
コード例 #14
0
ファイル: sockjsclient.go プロジェクト: rjeczalik/kite
// 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
}
コード例 #15
0
ファイル: kdb.go プロジェクト: algos/kdb
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
}
コード例 #16
0
ファイル: bot.go プロジェクト: ajm188/slack
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
}
コード例 #17
0
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)
	}
}
コード例 #18
0
ファイル: dialer.go プロジェクト: xyz12810/v2ray-core
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
}
コード例 #19
0
ファイル: gobot.go プロジェクト: adufrene/gobot
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
}
コード例 #20
0
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())
	}
}
コード例 #21
0
ファイル: client.go プロジェクト: morten-krogh/gowebsock
/* The client dials a connection to wsUri. The client starts a reader, a writer, and a standardInput reader.
 * Standard in is sent to the writer that will send it on the connection. The readerResult is printed to standard out.
 */
func client(wsUri string) {

	tlsConfig := tls.Config{}
	tlsConfig.InsecureSkipVerify = true
	dialer := websocket.Dialer{TLSClientConfig: &tlsConfig}
	requestHeader := http.Header{}
	requestHeader.Set("origin", "http://localhost/")
	conn, _, err := dialer.Dial(wsUri, requestHeader)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("The gowebsock client is connected to %s\n", wsUri)

	readerResultChan := make(chan readerResult)
	go reader(conn, readerResultChan)

	writerCommandChan := make(chan writerCommand)
	go writer(conn, writerCommandChan)

	stdinReaderChan := make(chan string)
	go stdinReader(stdinReaderChan)

	for {
		select {
		case stdinMessage := <-stdinReaderChan:
			var messageType int
			data := ""
			switch stdinMessage {
			case "close":
				messageType = 8
			case "ping":
				messageType = 9
			case "pong":
				messageType = 10
			default:
				messageType = 1
				data = stdinMessage
			}
			writerCommandChan <- writerCommand{false, messageType, []byte(data)}
		case readerResult := <-readerResultChan:
			if readerResult.err == nil {
				output := "Server: type = " + messageTypeString(readerResult.messageType) + ", data = " + string(readerResult.data) + "\n"
				fmt.Printf(output)
			} else {
				fmt.Printf("%s\n", readerResult.err)
				os.Exit(0)
			}
		}
	}
}
コード例 #22
0
ファイル: dialer.go プロジェクト: ylywyn/v2ray-core
func wsDial(ctx context.Context, dest v2net.Destination) (*wsconn, error) {
	src := internet.DialerSourceFromContext(ctx)
	wsSettings := internet.TransportSettingsFromContext(ctx).(*Config)

	commonDial := func(network, addr string) (net.Conn, error) {
		return internet.DialSystem(src, dest)
	}

	dialer := websocket.Dialer{
		NetDial:         commonDial,
		ReadBufferSize:  32 * 1024,
		WriteBufferSize: 32 * 1024,
	}

	protocol := "ws"

	if securitySettings := internet.SecuritySettingsFromContext(ctx); securitySettings != nil {
		tlsConfig, ok := securitySettings.(*v2tls.Config)
		if ok {
			protocol = "wss"
			dialer.TLSClientConfig = tlsConfig.GetTLSConfig()
			if dest.Address.Family().IsDomain() {
				dialer.TLSClientConfig.ServerName = dest.Address.Domain()
			}
		}
	}

	host := dest.NetAddr()
	if (protocol == "ws" && dest.Port == 80) || (protocol == "wss" && dest.Port == 443) {
		host = dest.Address.String()
	}
	uri := protocol + "://" + host + "/" + 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
}
コード例 #23
0
ファイル: client.go プロジェクト: djibi2/lxd
// WebsocketDial attempts to dial a websocket to a LXD instance, parsing
// LXD-style errors and returning them as go errors.
func WebsocketDial(dialer websocket.Dialer, url string) (*websocket.Conn, error) {
	conn, raw, err := dialer.Dial(url, http.Header{})
	if err != nil {
		_, err2 := HoistResponse(raw, Error)
		if err2 != nil {
			/* The response isn't one we understand, so return
			 * whatever the original error was. */
			return nil, err
		}

		return nil, err
	}
	return conn, err
}
コード例 #24
0
ファイル: nodnod_dial.go プロジェクト: mohabusama/nodnod
func main() {
	flag.Parse()

	log.SetLevel(log.InfoLevel)

	u := url.URL{Scheme: "ws", Host: *flAddress, Path: "/"}

	dialer := websocket.Dialer{}

	conn, _, err := dialer.Dial(u.String(), nil)
	if err != nil {
		log.Fatal("Failed to establish connection with server: ", err)
	}

	defer conn.Close()

	now := time.Now()

	go func() {
		defer conn.Close()
		for {
			var mresp stats.MessageResponse

			if err := conn.ReadJSON(&mresp); err != nil {
				log.Error("Error reading json response: ", err)
				break
			} else {
				log.Info("Received response from node: ", mresp.Host)
				log.Info("Duration:", time.Since(now))
				PrintStats(&mresp)
			}
		}

	}()

	for {
		var mreq stats.MessageRequest
		mreq.StatType = stats.ALL
		mreq.Type = stats.STATALL

		if err := conn.WriteJSON(&mreq); err != nil {
			log.Error("Failed to send req: ", err)
		} else {
			now = time.Now()
			log.Debug("Sent req: ", mreq)
		}

		time.Sleep(time.Duration(*flDuration) * time.Second)
	}
}
コード例 #25
0
ファイル: sockjsclient.go プロジェクト: GregWilson/kite
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 := randomStringLength(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 timeout, us a dial with a timeout
	if opts.Timeout != 0 {
		ws.NetDial = func(network, addr string) (net.Conn, error) {
			return net.DialTimeout(network, addr, opts.Timeout)
		}
		// this is used as Deadline inside gorillas dialer method
		ws.HandshakeTimeout = opts.Timeout
	}

	conn, _, err := ws.Dial(dialURL.String(), requestHeader)
	if err != nil {
		return nil, err
	}

	session := NewWebsocketSession(conn)
	session.id = sessionID
	return session, nil
}
コード例 #26
0
ファイル: main.go プロジェクト: ds0nt/webcommander-cli
func dial(url string) (*socketClient, *processor) {
	log.Printf("Dialing: %s", url)
	d := websocket.Dialer{}
	ws, _, err := d.Dial(url, nil)
	if err != nil {
		log.Panicf("An error occured while dialing: %s", err)
	}

	client := newClient(ws)
	processor := newProcessor(client)

	go processor.resultsTo(client)
	go client.read(processor)
	go client.write()
	return client, processor
}
コード例 #27
0
ファイル: consumer.go プロジェクト: GABONIA/cli
func (cnsmr *consumer) establishWebsocketConnection(path string, authToken string) (*websocket.Conn, error) {
	header := http.Header{"Origin": []string{"http://localhost"}, "Authorization": []string{authToken}}
	dialer := websocket.Dialer{NetDial: cnsmr.proxyDial, TLSClientConfig: cnsmr.tlsConfig}

	ws, resp, err := dialer.Dial(cnsmr.endpoint+path, header)

	if err == nil && cnsmr.callback != nil {
		cnsmr.callback()
	}
	if resp != nil && resp.StatusCode == http.StatusUnauthorized {
		bodyData, _ := ioutil.ReadAll(resp.Body)
		err = NewUnauthorizedError(string(bodyData))
	}

	return ws, err
}
コード例 #28
0
ファイル: client.go プロジェクト: cswank/quimby
func (c *Client) Connect(i int, cb func(gogadgets.Message)) error {
	c.disconnect = make(chan bool)
	c.connectedTo = i
	g := c.Nodes[i]

	a := fmt.Sprintf(c.addr, fmt.Sprintf("gadgets/%s/websocket", g.Id))
	u, err := url.Parse(a)
	if err != nil {
		return err
	}

	if u.Scheme == "https" {
		a = strings.Replace(a, "https", "wss", -1)
	} else {
		a = strings.Replace(a, "http", "ws", -1)
	}

	h := http.Header{"Origin": {a}, "Authorization": {c.token}}
	dialer := websocket.Dialer{
		Subprotocols:    []string{"p1", "p2"},
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}
	c.ws, _, err = dialer.Dial(a, h)
	if err != nil {
		return err
	}
	c.Out = make(chan gogadgets.Message)
	ws := make(chan gogadgets.Message)
	go c.listen(ws)
	go func() {
		for {
			select {
			case msg := <-c.Out:
				d, _ := json.Marshal(msg)
				c.ws.WriteMessage(websocket.TextMessage, d)
			case msg := <-ws:
				cb(msg)
			case <-c.disconnect:
				c.ws.Close()
				return
			}
		}
	}()
	return nil
}
コード例 #29
0
ファイル: jsonwebsocketimpl.go プロジェクト: cronosun/buranv1
func (self *jsonTestRunnerStruct) makeSureTheresAConnection() {
	if self.currentConnection == nil {
		log.Println("Connecting to server...")
		dialer := websocket.Dialer{
			HandshakeTimeout: 10 * time.Second,
		}
		header := make(http.Header)
		var err error
		self.currentConnection, _, err =
			dialer.Dial(fmt.Sprintf("%v%v", self.addr,
				self.url), header)
		log.Println("Connected to server.")
		if err != nil {
			panic(fmt.Sprintf("Error creating a connection: %v", err))
		}
	}
}
コード例 #30
0
ファイル: producer.go プロジェクト: JKolios/goLcdEvents
func ProducerSetupFuction(producer *producers.GenericProducer, config map[string]interface{}) {

	dialer := websocket.Dialer{}

	wsConnection, _, err := dialer.Dial(wsURI+config["PushbulletApiToken"].(string), nil)
	if err != nil {
		log.Fatal("PushbulletProducer: Error opening websocket connection:" + err.Error())
	}

	producer.RuntimeObjects["PushbulletApiToken"] = config["PushbulletApiToken"].(string)
	producer.RuntimeObjects["connection"] = wsConnection
	producer.RuntimeObjects["wsMessageChannel"] = make(chan wsMessage)
	producer.RuntimeObjects["lastcheckTimestamp"] = float64(time.Now().Unix())

	go wsMessagePump(producer)

}