当前位置: 首页>>代码示例>>Golang>>正文


Golang websocket.DialConfig函数代码示例

本文整理汇总了Golang中golang.org/x/net/websocket.DialConfig函数的典型用法代码示例。如果您正苦于以下问题:Golang DialConfig函数的具体用法?Golang DialConfig怎么用?Golang DialConfig使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了DialConfig函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Stream

func (c *Client) Stream(path string, headers map[string]string, in io.Reader, out io.WriteCloser) error {
	origin := fmt.Sprintf("https://%s", c.Host)
	endpoint := fmt.Sprintf("wss://%s%s", c.Host, path)

	config, err := websocket.NewConfig(endpoint, origin)

	if err != nil {
		return err
	}

	config.TlsConfig = &tls.Config{
		InsecureSkipVerify: true,
	}

	config.Header.Set("Version", c.Version)

	userpass := fmt.Sprintf("convox:%s", c.Password)
	userpass_encoded := base64.StdEncoding.EncodeToString([]byte(userpass))

	config.Header.Add("Authorization", fmt.Sprintf("Basic %s", userpass_encoded))

	for k, v := range headers {
		config.Header.Add(k, v)
	}

	config.TlsConfig = &tls.Config{
		InsecureSkipVerify: true,
	}

	var ws *websocket.Conn

	if proxy := os.Getenv("HTTPS_PROXY"); proxy != "" {
		ws, err = c.proxyWebsocket(config, proxy)
	} else {
		ws, err = websocket.DialConfig(config)
	}

	if err != nil {
		return err
	}

	defer ws.Close()

	var wg sync.WaitGroup

	if in != nil {
		go io.Copy(ws, in)
	}

	if out != nil {
		wg.Add(1)
		go copyAsync(out, ws, &wg)
	}

	wg.Wait()

	out.Close()

	return nil
}
开发者ID:cleblanc87,项目名称:rack,代码行数:60,代码来源:client.go

示例2: TestAppShellUnauthorizedError

func (s *S) TestAppShellUnauthorizedError(c *check.C) {
	a := app.App{
		Name:      "someapp",
		Platform:  "zend",
		TeamOwner: s.team.Name,
	}
	err := app.CreateApp(&a, s.user)
	c.Assert(err, check.IsNil)
	err = s.provisioner.AddUnits(&a, 1, "web", nil)
	c.Assert(err, check.IsNil)
	m := RunServer(true)
	server := httptest.NewServer(m)
	defer server.Close()
	testServerURL, err := url.Parse(server.URL)
	c.Assert(err, check.IsNil)
	url := fmt.Sprintf("ws://%s/apps/%s/shell?width=140&height=38&term=xterm", testServerURL.Host, a.Name)
	config, err := websocket.NewConfig(url, "ws://localhost/")
	c.Assert(err, check.IsNil)
	wsConn, err := websocket.DialConfig(config)
	c.Assert(err, check.IsNil)
	defer wsConn.Close()
	_, err = wsConn.Write([]byte("echo test"))
	c.Assert(err, check.IsNil)
	var result string
	err = tsurutest.WaitCondition(5*time.Second, func() bool {
		part, readErr := ioutil.ReadAll(wsConn)
		if readErr != nil {
			return false
		}
		result += string(part)
		return result == "Error: no token provided or session expired, please login again\n"
	})
	c.Assert(err, check.IsNil)
}
开发者ID:tsuru,项目名称:tsuru,代码行数:34,代码来源:shell_test.go

示例3: TestAppShellGenericError

func (s *S) TestAppShellGenericError(c *check.C) {
	m := RunServer(true)
	server := httptest.NewServer(m)
	defer server.Close()
	testServerURL, err := url.Parse(server.URL)
	c.Assert(err, check.IsNil)
	url := fmt.Sprintf("ws://%s/apps/someapp/shell?width=140&height=38&term=xterm", testServerURL.Host)
	config, err := websocket.NewConfig(url, "ws://localhost/")
	c.Assert(err, check.IsNil)
	config.Header.Set("Authorization", "bearer "+s.token.GetValue())
	wsConn, err := websocket.DialConfig(config)
	c.Assert(err, check.IsNil)
	defer wsConn.Close()
	_, err = wsConn.Write([]byte("echo test"))
	c.Assert(err, check.IsNil)
	var result string
	err = tsurutest.WaitCondition(5*time.Second, func() bool {
		part, readErr := ioutil.ReadAll(wsConn)
		if readErr != nil {
			c.Log(readErr)
			return false
		}
		result += string(part)
		return result == "Error: App someapp not found.\n"
	})
	c.Assert(err, check.IsNil)
}
开发者ID:tsuru,项目名称:tsuru,代码行数:27,代码来源:shell_test.go

示例4: main

func main() {
	wsConfig, _ := websocket.NewConfig("wss://www.example2.com/echo", "http://localhost/")
	wsConfig.TlsConfig = &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         "www.example2.com",
	}

	ws, err := websocket.DialConfig(wsConfig)
	if err != nil {
		log.Fatal(err)
	}

	message := []byte("hello, world!")
	_, err = ws.Write(message)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Send: %s\n", message)

	var msg = make([]byte, len(message))
	_, err = ws.Read(msg)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Receive: %s\n", msg)
}
开发者ID:ramr,项目名称:hello-websockets,代码行数:26,代码来源:client.go

示例5: readWebSocket

func readWebSocket(r *Reader, t *testing.T, fn func(*websocket.Conn), protocols ...string) ([]byte, error) {
	errCh := make(chan error, 1)
	s, addr := newServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		errCh <- r.Copy(w, req)
	}))
	defer s.Close()

	config, _ := websocket.NewConfig("ws://"+addr, "http://"+addr)
	config.Protocol = protocols
	client, err := websocket.DialConfig(config)
	if err != nil {
		return nil, err
	}
	defer client.Close()

	if fn != nil {
		fn(client)
	}

	data, err := ioutil.ReadAll(client)
	if err != nil {
		return data, err
	}
	return data, <-errCh
}
开发者ID:humblec,项目名称:kubernetes,代码行数:25,代码来源:stream_test.go

示例6: readWebSocket

func readWebSocket(r *Reader, t *testing.T, fn func(*websocket.Conn), protocols ...string) ([]byte, error) {
	errCh := make(chan error, 1)
	s, addr := newServer(func(ws *websocket.Conn) {
		cfg := ws.Config()
		cfg.Protocol = protocols
		go func() {
			err := <-r.err
			errCh <- err
		}()
		r.handle(ws)
	})
	defer s.Close()

	config, _ := websocket.NewConfig("ws://"+addr, "http://"+addr)
	client, err := websocket.DialConfig(config)
	if err != nil {
		return nil, err
	}
	defer client.Close()

	if fn != nil {
		fn(client)
	}

	data, err := ioutil.ReadAll(client)
	if err != nil {
		return data, err
	}
	return data, <-errCh
}
开发者ID:ncdc,项目名称:origin,代码行数:30,代码来源:stream_test.go

示例7: createWebsocketDialer

func createWebsocketDialer(cfg *websocket.Config, opts DialOpts) func(<-chan struct{}) (io.Closer, error) {
	openAttempt := utils.AttemptStrategy{
		Total: opts.Timeout,
		Delay: opts.RetryDelay,
	}
	return func(stop <-chan struct{}) (io.Closer, error) {
		for a := openAttempt.Start(); a.Next(); {
			select {
			case <-stop:
				return nil, parallel.ErrStopped
			default:
			}
			logger.Infof("dialing %q", cfg.Location)
			conn, err := websocket.DialConfig(cfg)
			if err == nil {
				return conn, nil
			}
			if a.HasNext() {
				logger.Debugf("error dialing %q, will retry: %v", cfg.Location, err)
			} else {
				logger.Infof("error dialing %q: %v", cfg.Location, err)
				return nil, errors.Errorf("unable to connect to %q", cfg.Location)
			}
		}
		panic("unreachable")
	}
}
开发者ID:claudiu-coblis,项目名称:juju,代码行数:27,代码来源:apiclient.go

示例8: expectWebSocketFrames

func expectWebSocketFrames(r *Reader, t *testing.T, fn func(*websocket.Conn), frames [][]byte, protocols ...string) error {
	errCh := make(chan error, 1)
	s, addr := newServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		errCh <- r.Copy(w, req)
	}))
	defer s.Close()

	config, _ := websocket.NewConfig("ws://"+addr, "http://"+addr)
	config.Protocol = protocols
	ws, err := websocket.DialConfig(config)
	if err != nil {
		return err
	}
	defer ws.Close()

	if fn != nil {
		fn(ws)
	}

	for i := range frames {
		var data []byte
		if err := websocket.Message.Receive(ws, &data); err != nil {
			return err
		}
		if !reflect.DeepEqual(frames[i], data) {
			return fmt.Errorf("frame %d did not match expected: %v", data, err)
		}
	}
	var data []byte
	if err := websocket.Message.Receive(ws, &data); err != io.EOF {
		return fmt.Errorf("expected no more frames: %v (%v)", err, data)
	}
	return <-errCh
}
开发者ID:humblec,项目名称:kubernetes,代码行数:34,代码来源:stream_test.go

示例9: createWebsocketDialer

func createWebsocketDialer(cfg *websocket.Config, opts DialOpts) func(<-chan struct{}) (io.Closer, error) {
	// TODO(katco): 2016-08-09: lp:1611427
	openAttempt := utils.AttemptStrategy{
		Total: opts.Timeout,
		Delay: opts.RetryDelay,
	}
	return func(stop <-chan struct{}) (io.Closer, error) {
		for a := openAttempt.Start(); a.Next(); {
			select {
			case <-stop:
				return nil, parallel.ErrStopped
			default:
			}
			logger.Infof("dialing %q", cfg.Location)
			conn, err := websocket.DialConfig(cfg)
			if err == nil {
				return conn, nil
			}
			if !a.HasNext() || isX509Error(err) {
				// We won't reconnect when there's an X509 error
				// because we're not going to succeed if we retry
				// in that case.
				logger.Infof("error dialing %q: %v", cfg.Location, err)
				return nil, errors.Annotatef(err, "unable to connect to API")
			}
		}
		panic("unreachable")
	}
}
开发者ID:kat-co,项目名称:juju,代码行数:29,代码来源:apiclient.go

示例10: testWebSocketServer

func testWebSocketServer(hdrs map[string]string, expected string) {
	origin := "http://127.0.0.1/"
	url := "ws://" + string(_defaultFrontdAddr) + "/echo"
	cfg, err := websocket.NewConfig(url, origin)
	if err != nil {
		panic(err)
	}

	for k, v := range hdrs {
		cfg.Header.Set(k, v)
	}

	ws, err := websocket.DialConfig(cfg)
	if err != nil {
		panic(err)
	}
	if _, err := ws.Write([]byte(expected)); err != nil {
		panic(err)
	}
	var msg = make([]byte, len(expected))
	var n int
	if n, err = ws.Read(msg); err != nil {
		panic(err)
	}

	if expected != string(msg[:n]) {
		log.Println(string(msg[:n]))
		log.Println(expected)
		panic(fmt.Errorf("websocket reply not match: %s", string(msg[:n])))
	}

}
开发者ID:uin57,项目名称:frontd,代码行数:32,代码来源:main_test.go

示例11: cli

func cli(args CommandLineArguments, wg *sync.WaitGroup) {
	defer wg.Done()
	cfg, err := websocket.NewConfig(args.server, "wss://localhost")
	if err != nil {
		panic(err)
	}
	cert, err := tls.LoadX509KeyPair("server.pem", "server.key")
	if err != nil {
		panic(err)
	}
	config := tls.Config{Certificates: []tls.Certificate{cert}}
	config.InsecureSkipVerify = true
	cfg.TlsConfig = &config
	ws, err := websocket.DialConfig(cfg)
	if err != nil {
		panic(err)
	}
	if args.msg != "" {
		log.Println("Write data to websocket")
		_, err = ws.Write([]byte(args.msg))
		if err != nil {
			panic(err)
		}
	}
	if args.file != "" {
		go func() {
			f, err := os.Open(args.file)
			if err != nil {
				panic(err)
			}
			defer f.Close()
			s := bufio.NewScanner(f)
			for s.Scan() {
				time.Sleep(time.Duration(args.delay) * time.Second)
				_, err = ws.Write([]byte(s.Text()))
				if err != nil {
					panic(err)
				}
			}
		}()
	}
	ws.SetReadDeadline(time.Now().Add(time.Second * time.Duration(args.timeOut)))
	msgOut := make([]byte, 16384)
	for {
		n, err := ws.Read(msgOut)
		log.Println("Read bytes:", n)
		if err == io.EOF {
			log.Println("Reading finished")
			break
		}
		if err != nil {
			log.Println(err)
			break
		}
		log.Println(string(msgOut[:n]))
	}
	log.Println("Closing connection")
	ws.Close()
}
开发者ID:vsysoev,项目名称:goeventstore,代码行数:59,代码来源:wsclient.go

示例12: TestBase64Conn

func TestBase64Conn(t *testing.T) {
	conn := NewConn(NewDefaultChannelProtocols([]ChannelType{ReadWriteChannel, ReadWriteChannel}))
	s, addr := newServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		conn.Open(w, req)
	}))
	defer s.Close()

	config, err := websocket.NewConfig("ws://"+addr, "http://localhost/")
	if err != nil {
		t.Fatal(err)
	}
	config.Protocol = []string{"base64.channel.k8s.io"}
	client, err := websocket.DialConfig(config)
	if err != nil {
		t.Fatal(err)
	}
	defer client.Close()

	<-conn.ready
	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		defer wg.Done()
		data, err := ioutil.ReadAll(conn.channels[0])
		if err != nil {
			t.Fatal(err)
		}
		if !reflect.DeepEqual(data, []byte("client")) {
			t.Errorf("unexpected server read: %s", string(data))
		}
	}()

	clientData := base64.StdEncoding.EncodeToString([]byte("client"))
	if n, err := client.Write(append([]byte{'0'}, clientData...)); err != nil || n != len(clientData)+1 {
		t.Fatalf("%d: %v", n, err)
	}

	wg.Add(1)
	go func() {
		defer wg.Done()
		if n, err := conn.channels[1].Write([]byte("server")); err != nil && n != 6 {
			t.Fatalf("%d: %v", n, err)
		}
	}()

	data := make([]byte, 1024)
	if n, err := io.ReadAtLeast(client, data, 9); n != 9 || err != nil {
		t.Fatalf("%d: %v", n, err)
	}
	expect := []byte(base64.StdEncoding.EncodeToString([]byte("server")))

	if !reflect.DeepEqual(data[:9], append([]byte{'1'}, expect...)) {
		t.Errorf("unexpected client read: %v", data[:9])
	}

	client.Close()
	wg.Wait()
}
开发者ID:humblec,项目名称:kubernetes,代码行数:58,代码来源:conn_test.go

示例13: TestBase64Conn

func TestBase64Conn(t *testing.T) {
	conn := NewConn(ReadWriteChannel, ReadWriteChannel)
	// TODO: Uncomment next two lines and remove third line when fix #19254
	// s, addr := newServer(conn.handle)
	// defer s.Close()
	_, addr := newServer(conn.handle)

	config, err := websocket.NewConfig("ws://"+addr, "http://localhost/")
	if err != nil {
		t.Fatal(err)
	}
	config.Protocol = []string{"base64.channel.k8s.io"}
	client, err := websocket.DialConfig(config)
	if err != nil {
		t.Fatal(err)
	}
	defer client.Close()

	<-conn.ready
	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		defer wg.Done()
		data, err := ioutil.ReadAll(conn.channels[0])
		if err != nil {
			t.Fatal(err)
		}
		if !reflect.DeepEqual(data, []byte("client")) {
			t.Errorf("unexpected server read: %s", string(data))
		}
	}()

	clientData := base64.StdEncoding.EncodeToString([]byte("client"))
	if n, err := client.Write(append([]byte{'0'}, clientData...)); err != nil || n != len(clientData)+1 {
		t.Fatalf("%d: %v", n, err)
	}

	wg.Add(1)
	go func() {
		defer wg.Done()
		if n, err := conn.channels[1].Write([]byte("server")); err != nil && n != 6 {
			t.Fatalf("%d: %v", n, err)
		}
	}()

	data := make([]byte, 1024)
	if n, err := io.ReadAtLeast(client, data, 9); n != 9 || err != nil {
		t.Fatalf("%d: %v", n, err)
	}
	expect := []byte(base64.StdEncoding.EncodeToString([]byte("server")))

	if !reflect.DeepEqual(data[:9], append([]byte{'1'}, expect...)) {
		t.Errorf("unexpected client read: %v", data[:9])
	}

	client.Close()
	wg.Wait()
}
开发者ID:CNDonny,项目名称:scope,代码行数:58,代码来源:conn_test.go

示例14: main

func main() {
	if *user == "" {
		log.Fatalf("No user/pass\n")
	}

	originURL, err := url.Parse("https://" + *ipAddress + "/api/v1/watch/namespaces/decap/pods?watch=true&labelSelector=type=decap-build")
	if err != nil {
		log.Fatal(err)
	}
	serviceURL, err := url.Parse("wss://" + *ipAddress + "/api/v1/watch/namespaces/decap/pods?watch=true&labelSelector=type=decap-build")
	if err != nil {
		log.Fatal(err)
	}

	cfg := websocket.Config{
		Location:  serviceURL,
		Origin:    originURL,
		TlsConfig: &tls.Config{InsecureSkipVerify: true},
		Header:    map[string][]string{"Authorization": []string{"Basic " + base64.StdEncoding.EncodeToString([]byte(*user+":"+*password))}},
		Version:   websocket.ProtocolVersionHybi13,
	}

	conn, err := websocket.DialConfig(&cfg)
	if err != nil {
		log.Fatalf("Error opening connection: %v\n", err)
	}

	// returns a Pod Object
	var msg string
	for {
		err := websocket.Message.Receive(conn, &msg)
		if err != nil {
			if err == io.EOF {
				break
			}
			log.Println("Couldn't receive msg " + err.Error())
			break
		}
		var pod Pod
		if err := json.Unmarshal([]byte(msg), &pod); err != nil {
			log.Println(err)
			continue
		}
		var deletePod bool
		for _, status := range pod.Object.Status.Statuses {
			if status.Name == "build-server" && status.State.Terminated.ContainerID != "" {
				deletePod = true
				break
			}
		}
		if deletePod {
			log.Printf("Would delete:  %+v\n", pod)
		}

	}
	os.Exit(0)
}
开发者ID:ae6rt,项目名称:gowebsockets,代码行数:57,代码来源:main.go

示例15: RegisterAndListen

// Register target type on vmt server and start to listen for server message
func (wsc *WebSocketCommunicator) RegisterAndListen(registrationMessage *MediationClientMessage) {
	// vmtServerUrl := "ws://10.10.173.154:8080/vmturbo/remoteMediation"
	vmtServerUrl := "ws://" + wsc.VmtServerAddress + "/vmturbo/remoteMediation"
	localAddr := wsc.LocalAddress

	glog.V(3).Infof("Dial Server: %s", vmtServerUrl)

	config, err := websocket.NewConfig(vmtServerUrl, localAddr)
	if err != nil {
		glog.Fatal(err)
	}
	usrpasswd := []byte(wsc.ServerUsername + ":" + wsc.ServerPassword)

	config.Header = http.Header{
		"Authorization": {"Basic " + base64.StdEncoding.EncodeToString(usrpasswd)},
	}
	webs, err := websocket.DialConfig(config)

	// webs, err := websocket.Dial(vmtServerUrl, "", localAddr)
	if err != nil {
		glog.Error(err)
		if webs == nil {
			glog.Error("The websocket is null, reset")
		}
		wsc.CloseAndRegisterAgain(registrationMessage)
	}
	wsc.ws = webs

	glog.V(3).Infof("Send registration info")
	wsc.SendClientMessage(registrationMessage)

	var msg = make([]byte, 1024)
	var n int

	// main loop for listening server message.
	for {
		if n, err = wsc.ws.Read(msg); err != nil {
			glog.Error(err)
			//glog.Fatal(err.Error())
			//re-establish connection when error
			glog.V(3).Infof("Error happened, re-establish websocket connection")
			break
		}
		serverMsg := &MediationServerMessage{}
		err = proto.Unmarshal(msg[:n], serverMsg)
		if err != nil {
			glog.Error("Received unmarshalable error, please make sure you are running the latest VMT server")
			glog.Fatal("unmarshaling error: ", err)
		}
		//Spawn a separate go routine to handle the server message
		go wsc.handleServerMessage(serverMsg, registrationMessage)
		glog.V(3).Infof("Continue listen from server...")
	}
	wsc.CloseAndRegisterAgain(registrationMessage)
}
开发者ID:enlinxu,项目名称:vmturbo-go-sdk,代码行数:56,代码来源:communicator.go


注:本文中的golang.org/x/net/websocket.DialConfig函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。