• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang websocket.NewClient函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: newClientConnection

func newClientConnection(connectionUrl string) (conn *websocket.Conn) {
	u, err := url.Parse(connectionUrl)
	if err != nil {
		Error.Println(err)
	}

	Trace.Printf("url for new client connection is %+v\n", u)

	Info.Println("Attempting to dial " + u.Host)

	rawConn, err := net.Dial("tcp", u.Host)
	if err != nil {
		Error.Printf("Failed to dial %s. Error: %+v\n", err)
		return nil
	}

	wsHeaders := http.Header{
		"Origin": {u.Host},
		// your milage may differ
		"Sec-WebSocket-Extensions": {"permessage-deflate; client_max_window_bits, x-webkit-deflate-frame"},
	}

	wsConn, resp, err := websocket.NewClient(rawConn, u, wsHeaders, 1024, 1024)

	if err != nil {
		Error.Printf("websocket.NewClient Error: %s\nResp:%+v", err, resp)
	}

	Info.Printf("Successfully connected to %+v", wsConn.RemoteAddr())

	return wsConn
}
开发者ID:etinlb,项目名称:go_server_experiment,代码行数:32,代码来源:server_handlers.go


示例2: openSocketToContainer

func (c *ContainerConnection) openSocketToContainer() error {
	id := c.id
	endpoint := GlobalConfig.GetDockerEndpoint()
	u, err := url.Parse(endpoint + "/v" + DockerApiVersion + "/containers/" + id + "/attach/ws?logs=0&stderr=1&stdout=1&stream=1&stdin=1")
	if err != nil {
		return err
	}

	rawConn, err := net.Dial("tcp", u.Host)
	if err != nil {
		return err
	}

	wsHeaders := http.Header{
		"Origin": {"http://localhost:4500"},
	}

	wsConn, resp, err := websocket.NewClient(rawConn, u, wsHeaders, 1024, 1024)

	if err != nil {
		Log.Error("Unable to connect", resp, err)
	}
	c.container = wsConn
	return err
}
开发者ID:nishizhen,项目名称:codetainer,代码行数:25,代码来源:container.go


示例3: NewWebsocket

func (b BackendController) NewWebsocket(connectionUrl string) (*websocket.Conn, error) {
	u, err := url.Parse(connectionUrl)
	if err != nil {
		log.Println(err)
		return nil, errors.New("Cannot parse connection url" + connectionUrl)
	}
	log.Println(u)

	log.Println(u.Host)
	rawConn, err := net.Dial("tcp", u.Host)
	if err != nil {
		log.Println(err)
		return nil, errors.New("cannot dial " + u.Host)
	}

	wsHeaders := http.Header{
		"Origin": {u.Host},
		// your milage may differ
		"Sec-WebSocket-Extensions": {
			"permessage-deflate; client_max_window_bits, x-webkit-deflate-frame"},
	}

	wsConn, resp, err := websocket.NewClient(rawConn, u, wsHeaders, 1024, 1024)

	if err != nil {

		return nil, fmt.Errorf("websocket.NewClient Error: %s\nResp:%+v", err, resp)

	}

	b.AddNewConnection(wsConn)

	return wsConn, nil
}
开发者ID:etinlb,项目名称:go_server_experiment,代码行数:34,代码来源:main.go


示例4: NewClient

func NewClient(originURL, targetURL string, settings map[string]interface{}) (c *websocket.Conn, response *http.Response, err error) {
	u, err := url.Parse(targetURL)
	if err != nil {
		return nil, nil, err
	}

	dialer := net.Dialer{}

	timeoutInterface, ok := settings["Timeout"]
	if ok {
		dialer.Timeout = timeoutInterface.(time.Duration)
	}

	keepAliveInterface, ok := settings["KeepAlive"]
	if ok {
		dialer.KeepAlive = keepAliveInterface.(time.Duration)
	}

	rawConn, err := dialer.Dial("tcp", u.Host)
	if err != nil {
		logrus.WithFields(logrus.Fields{
			"Error": err.Error(),
		}).Errorf("TCP connection error when dialing %v", u.Host)

		return nil, nil, err
	}

	wsHeaders := http.Header{
		"Origin": {originURL},
		// your milage may differ
		"Sec-WebSocket-Extensions": {"permessage-deflate; client_max_window_bits, x-webkit-deflate-frame"},
	}

	return websocket.NewClient(rawConn, u, wsHeaders, 1024, 1024)
}
开发者ID:actaeon,项目名称:resourced,代码行数:35,代码来源:wstrafficker.go


示例5: connect

func (wi *websocketInstance) connect() {
	//keep trying to get a connection

	var conn net.Conn
	var dialConnection func()
	dialConnection = func() {
		_conn, err := net.Dial("tcp", wi.address+":"+wi.port)
		if err != nil {
			defer dialConnection()
			time.Sleep(pingPeriod)
			return
		}
		conn = _conn
	}
	dialConnection()

	log.Println("connection found")

	site, err := url.Parse("ws://" + wi.address + ":" + wi.port + wi.path)

	wi.socket, _, err = websocket.NewClient(conn, site, nil, bufferSize, bufferSize)

	if err != nil {
		if _, ok := err.(websocket.HandshakeError); !ok {
			log.Println(err)
		}
		return
	}

	go wi.writeHandler()
	go wi.readHandler()
}
开发者ID:dazzaji,项目名称:Flare,代码行数:32,代码来源:websockets.go


示例6: connectOnce

func (ws *WSConnection) connectOnce(r *Room, try int) error {
	r.Logger.Infof("Connecting to room %s...", r.RoomName)
	tlsConn, err := tls.Dial("tcp", "euphoria.io:443", &tls.Config{})
	if err != nil {
		return err
	}
	roomURL, err := url.Parse(fmt.Sprintf("wss://euphoria.io/room/%s/ws", r.RoomName))
	if err != nil {
		return err
	}
	wsConn, _, err := websocket.NewClient(tlsConn, roomURL, http.Header{}, 4096, 4096)
	if err != nil {
		return err
	}
	if err := r.Ctx.Check("connectOnce", try); err != nil {
		return err
	}
	ws.conn = wsConn
	if r.password != "" {
		if _, err := r.sendAuth(); err != nil {
			return err
		}
	}
	if _, err := r.sendNick(); err != nil {
		return err
	}
	return nil
}
开发者ID:CylonicRaider,项目名称:gobot,代码行数:28,代码来源:connection.go


示例7: Connect

func (c *GremlinClient) Connect() {
	host := c.Addr + ":" + strconv.FormatInt(int64(c.Port), 10)

	conn, err := net.Dial("tcp", host)
	if err != nil {
		logging.GetLogger().Error("Connection to the WebSocket server failed: %s", err.Error())
		return
	}

	endpoint := "ws://" + host
	u, err := url.Parse(endpoint)
	if err != nil {
		logging.GetLogger().Error("Unable to parse the WebSocket Endpoint %s: %s", endpoint, err.Error())
		return
	}

	wsConn, _, err := websocket.NewClient(conn, u, http.Header{}, 0, 4096)
	if err != nil {
		logging.GetLogger().Error("Unable to create a WebSocket connection %s : %s", endpoint, err.Error())
		return
	}

	logging.GetLogger().Info("Connected to gremlin server %s:%d", c.Addr, c.Port)

	c.wsConn = wsConn
}
开发者ID:mestery,项目名称:skydive,代码行数:26,代码来源:client.go


示例8: TestWebsocketQuery

func TestWebsocketQuery(t *testing.T) {
	w := test.GetWorld(t)
	pn := w.NewPermanode(t)
	test.MustRunCmd(t, w.Cmd("camput", "attr", pn.String(), "tag", "foo"))

	check := func(err error) {
		if err != nil {
			t.Fatal(err)
		}
	}

	const bufSize = 1 << 20

	c, err := net.Dial("tcp", w.Addr())
	if err != nil {
		t.Fatalf("Dial: %v", err)
	}
	defer c.Close()

	wc, _, err := websocket.NewClient(c, &url.URL{Host: w.Addr(), Path: w.SearchHandlerPath() + "ws"}, nil, bufSize, bufSize)
	check(err)

	msg, err := wc.NextWriter(websocket.TextMessage)
	check(err)

	_, err = msg.Write([]byte(`{"tag": "foo", "query": { "expression": "tag:foo" }}`))
	check(err)
	check(msg.Close())

	errc := make(chan error, 1)
	go func() {
		inType, inMsg, err := wc.ReadMessage()
		if err != nil {
			errc <- err
			return
		}
		if !strings.HasPrefix(string(inMsg), `{"tag":"_status"`) {
			errc <- fmt.Errorf("unexpected message type=%d msg=%q, wanted status update", inType, inMsg)
			return
		}
		inType, inMsg, err = wc.ReadMessage()
		if err != nil {
			errc <- err
			return
		}
		if strings.Contains(string(inMsg), pn.String()) {
			errc <- nil
			return
		}
		errc <- fmt.Errorf("unexpected message type=%d msg=%q", inType, inMsg)
	}()
	select {
	case err := <-errc:
		if err != nil {
			t.Error(err)
		}
	case <-time.After(5 * time.Second):
		t.Error("timeout")
	}
}
开发者ID:camlistore,项目名称:camlistore,代码行数:60,代码来源:camlistore_test.go


示例9: NewConnection

func NewConnection(pin string) (*Connection, error) {
	gameId, err := strconv.Atoi(pin)
	if err != nil {
		return nil, err
	}

	conn, err := tls.Dial("tcp", "kahoot.it:443", nil)
	if err != nil {
		return nil, err
	}

	url, _ := url.Parse("wss://kahoot.it/cometd")
	reqHeader := http.Header{}
	reqHeader.Set("Origin", "https://kahoot.it")
	reqHeader.Set("Cookie", "no.mobitroll.session="+pin)
	ws, _, err := websocket.NewClient(conn, url, reqHeader, 100, 100)
	if err != nil {
		return nil, err
	}

	incoming := make(chan incomingData, 100)
	res := &Connection{ws, 0, gameId, "", incoming}
	go res.readLoop()
	return res, nil
}
开发者ID:nick2228,项目名称:kahoot-hack,代码行数:25,代码来源:connection.go


示例10: openConnection

// Open WebSocket connection to Kubernetes API server
func openConnection(endpoint string) *websocket.Conn {
	u, err := url.Parse(endpoint)
	if err != nil {
		log.Fatal(err)
	}

	log.Printf("Connect to K8S master host: %v", u.Host)
	rawConn, err := net.Dial("tcp", u.Host)
	if err != nil {
		log.Fatal(err)
	}

	wsHeaders := http.Header{
		"Origin":                   {endpoint},
		"Sec-WebSocket-Extensions": {"permessage-deflate; client_max_window_bits, x-webkit-deflate-frame"},
	}

	wsConn, resp, err := websocket.NewClient(rawConn, u, wsHeaders, 1024, 1024)
	if err != nil {
		log.Fatalf("websocket.NewClient Error: %s\nResp:%+v", err, resp)

	}

	return wsConn
}
开发者ID:rainbean,项目名称:Kube2Vulcan,代码行数:26,代码来源:kube2vulcan.go


示例11: openSocketToContainer

func (c *ContainerConnection) openSocketToContainer() error {
	id := c.id
	endpoint := GlobalConfig.GetDockerEndpoint()
	u, err := url.Parse(endpoint + "/v" + DockerApiVersion + "/containers/" + id + "/attach/ws?logs=0&stderr=1&stdout=1&stream=1&stdin=1")
	if err != nil {
		return err
	}

	var rawConn net.Conn
	if GlobalConfig.DockerServerUseHttps {
		rawConn, err = tls.Dial("tcp", u.Host, GlobalConfig.tlsConfig)
	} else {
		rawConn, err = net.Dial("tcp", u.Host)
	}
	if err != nil {
		return err
	}

	wsHeaders := http.Header{
		"Origin": {endpoint},
	}

	wsConn, resp, err := websocket.NewClient(rawConn, u, wsHeaders, 1024, 1024)

	if err != nil {
		Log.Error("Unable to connect", resp, err)
	}
	c.container = wsConn
	return err
}
开发者ID:mslsoftware,项目名称:codetainer,代码行数:30,代码来源:container.go


示例12: wsClient

func wsClient(conn net.Conn, host string) (*wsConn, error) {
	c, resp, err := websocket.NewClient(conn, &url.URL{Scheme: "ws", Host: host, Path: "/ws"}, nil, 4096, 4096)
	if err != nil {
		return nil, err
	}
	resp.Body.Close()

	return &wsConn{conn: c}, nil
}
开发者ID:jim1568cas,项目名称:gost,代码行数:9,代码来源:ws.go


示例13: connectWebsocketNoHandshake

func connectWebsocketNoHandshake(t *testing.T, server *httptest.Server, header http.Header) (*websocket.Conn, error) {
	conn := connectToTestServer(t, server)
	url := urlMustParse(server.URL)
	url.Path = "/ctrl"
	url.Scheme = "ws"
	ws, _, err := websocket.NewClient(conn, url, header, 1024, 1024)
	if err != nil {
		return nil, fmt.Errorf("raw websocket client: %v", err)
	}
	return ws, nil
}
开发者ID:hraban,项目名称:lush,代码行数:11,代码来源:websocket_test.go


示例14: connectWebsocket

func connectWebsocket(server *httptest.Server, path string) (*websocket.Conn, error) {
	conn, err := connectToTestServer(server)
	if err != nil {
		return nil, err
	}
	url := urlMustParse(server.URL + path)
	ws, _, err := websocket.NewClient(conn, url, nil, 1024, 1024)
	if err != nil {
		return nil, err
	}
	return ws, nil
}
开发者ID:hraban,项目名称:websockethub,代码行数:12,代码来源:websocket_test.go


示例15: newClient

func newClient() (*websocket.Conn, error) {
	u, _ := url.Parse(WSURL)
	conn, err := net.Dial("tcp", ADDR)

	if err != nil {
		return nil, err
	}

	header := http.Header{"Origin": {ORIGIN}}
	ws, _, err := websocket.NewClient(conn, u, header, 1024, 1024)
	return ws, err
}
开发者ID:russellwmy,项目名称:goddp,代码行数:12,代码来源:websocket_test.go


示例16: startClient

func startClient() {
	fmt.Println("start...")
	// rcount = 0
	// scount = 0
	url, err := url.Parse("http://localhost:4000/")
	if err != nil {
		fmt.Println("url parse failed")
		fmt.Println(err.Error())
		return
	}

	conn, err := net.Dial("tcp", url.Host)
	if err != nil {
		fmt.Println("dial failed")
		fmt.Println(err.Error())
		return
	}
	if conn == nil {
		fmt.Println("Conn nil")
	}

	requestHeader := http.Header{
		"Origin":                   {"http://localhost:4000"},
		"Sec-WebSocket-Extensions": {"permessage-deflate; client_max_window_bits, x-webkit-deflate-frame"},
	}

	wsConn, response, err := websocket.NewClient(conn, url, requestHeader, 1024, 1024)
	if err != nil {
		fmt.Println("newClient failed")
		fmt.Println(response)
		fmt.Println(err.Error())
	}
	// fmt.Println("Creating Channels")
	recd := make(chan []byte, 1)
	quit := make(chan bool, 2)

	wsConn.WriteMessage(websocket.TextMessage, []byte("Hey"))
	// scount++
	// fmt.Printf("s: %d\n", scount)

	addReadListener(recd, quit)
	sendHeartbeats(wsConn)

	for {
		_, received, err := wsConn.ReadMessage()
		if err != nil {
			fmt.Println("read failed")
			fmt.Println(err.Error())
			break
		}
		recd <- received
	}
}
开发者ID:tanmaybinaykiya,项目名称:websocket,代码行数:53,代码来源:client.go


示例17: connect

func (self *ClientWebsocket) connect() (ws *websocket.Conn, e error) {
	c, e := net.Dial("tcp", self.url.Host)
	if e != nil {
		return nil, fmt.Errorf("net.Dial failed: %s", e.Error())
	}

	ws, _, e = websocket.NewClient(c, self.url, *self.httpHeader, 1024, 1024)
	if e != nil {
		return nil, fmt.Errorf("websocket.NewClient failed: %s", e)
	}

	return ws, nil
}
开发者ID:vany-egorov,项目名称:absolut,代码行数:13,代码来源:client-websocket.go


示例18: Connect

// Connect opens a connection to the backend and upgrades it to a websocket. Calls to
// 'MakeRequest' can be made after calling this, but responss will not be
// receivable until 'Serve' is also called.
func (cs *ClientServerImpl) Connect() error {
	parsedURL, err := url.Parse(cs.URL)
	if err != nil {
		return err
	}

	// NewRequest never returns an error if the url parses and we just verified
	// it did above
	request, _ := http.NewRequest("GET", cs.URL, nil)
	// Sign the request; we'll send its headers via the websocket client which includes the signature
	utils.SignHTTPRequest(request, cs.Region, ServiceName, cs.CredentialProvider)

	// url.Host might not have the port, but tls.Dial needs it
	dialHost := parsedURL.Host
	if !strings.Contains(dialHost, ":") {
		dialHost += ":443"
	}

	timeoutDialer := &net.Dialer{Timeout: wsConnectTimeout}
	log.Info("Creating poll dialer", "host", parsedURL.Host)
	wsConn, err := tls.DialWithDialer(timeoutDialer, "tcp", dialHost, &tls.Config{InsecureSkipVerify: cs.AcceptInvalidCert})
	if err != nil {
		return err
	}

	websocketConn, httpResponse, err := websocket.NewClient(wsConn, parsedURL, request.Header, readBufSize, writeBufSize)
	if httpResponse != nil {
		defer httpResponse.Body.Close()
	}
	if err != nil {
		defer wsConn.Close()
		var resp []byte
		if httpResponse != nil {
			var readErr error
			resp, readErr = ioutil.ReadAll(httpResponse.Body)
			if readErr != nil {
				return errors.New("Unable to read websocket connection: " + readErr.Error() + ", " + err.Error())
			}
			// If there's a response, we can try to unmarshal it into one of the
			// modeled error types
			possibleError, _, decodeErr := DecodeData(resp, cs.TypeDecoder)
			if decodeErr == nil {
				return cs.NewError(possibleError)
			}
		}
		log.Warn("Error creating a websocket client", "err", err)
		return errors.New(string(resp) + ", " + err.Error())
	}
	cs.Conn = websocketConn
	return nil
}
开发者ID:shufo,项目名称:amazon-ecs-agent,代码行数:54,代码来源:client.go


示例19: handleRequest

// Handles incoming requests.
func handleRequest(conn net.Conn, rhost string) {
	fmt.Println("TCP connection received")
	defer func() { fmt.Println("Connection closed") }()
	defer conn.Close()

	ws_url, err := url.Parse(rhost)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	wsConn, err := net.Dial(CONN_TYPE, ws_url.Host)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	defer wsConn.Close()

	REQUEST_HEADERS := map[string][]string{
		"Sec-Websocket-Protocol": []string{"binary", "base64"},
	}
	ws, response, err := websocket.NewClient(wsConn, ws_url, REQUEST_HEADERS, BUFFER_SIZE, BUFFER_SIZE)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	defer ws.Close()

	protocol_arr := response.Header["Sec-Websocket-Protocol"]
	var protocol string
	if len(protocol_arr) > 0 {
		protocol = protocol_arr[0]
	}

	var messageType int
	if protocol == "base64" {
		messageType = websocket.TextMessage
	} else if protocol == "binary" {
		messageType = websocket.BinaryMessage
	} else {
		fmt.Println("Expected Sec-Websocket-Protocol header value of binary or base64, got:")
		fmt.Println(response.Header)
		return
	}

	fmt.Println("Websocket connection established, proxying...")
	var stopChan = make(chan int)
	go pipe_to_ws(conn, ws, messageType, stopChan)
	pipe_to_net(conn, ws, messageType, stopChan)
}
开发者ID:liu-junyong,项目名称:tcp2ws-go,代码行数:51,代码来源:tcp2ws.go


示例20: StartAgent

func StartAgent(pURL *url.URL, subdomain, serverAddr string, remoteListenPort int, data string) {
	log.Debug("start proxy", pURL)
	if !regexp.MustCompile("^http[s]://").MatchString(serverAddr) {
		serverAddr = "http://" + serverAddr
	}
	sURL, err := url.Parse(serverAddr)
	if err != nil {
		log.Fatal(err)
	}

	sURL.Path = "/ws"
	log.Debug("server host:", sURL.Host)
	conn, err := net.Dial("tcp", sURL.Host)
	if err != nil {
		log.Fatal(err)
	}
	// specify remote listen port
	sURL.Scheme = "ws"
	query := sURL.Query()
	query.Add("protocol", pURL.Scheme)
	query.Add("subdomain", subdomain)
	query.Add("data", data)
	if remoteListenPort != 0 {
		query.Add("port", strconv.Itoa(remoteListenPort))
	}
	sURL.RawQuery = query.Encode()

	log.Debug(sURL)
	wsclient, _, err := websocket.NewClient(conn, sURL, nil, 1024, 1024)
	if err != nil {
		log.Fatal(err)
	}
	defer wsclient.Close()
	go idleWsSend(wsclient)

	for {
		var msg Msg
		if err := wsclient.ReadJSON(&msg); err != nil {
			fmt.Println("client exit: " + err.Error())
			break
		}
		log.Debug("recv:", msg)

		// sURL: serverURL
		rnl := NewRevNetListener()
		go handleRevConn(pURL, rnl)
		handleWsMsg(msg, sURL, rnl)
	}
}
开发者ID:Andy-hpliu,项目名称:proxylocal,代码行数:49,代码来源:client.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang websocket.Upgrade函数代码示例发布时间:2022-05-23
下一篇:
Golang websocket.IsUnexpectedCloseError函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap