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

Golang websocket.Dial函数代码示例

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

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



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

示例1: main

func main() {
	for i := 0; i < 2000; i++ {
		go func(num int) {
			t := time.Now().UnixNano()
			ws, err := websocket.Dial("wss://ws.binaryws.com/websockets/v3?app_id=1&l=EN", "", "http://load_test")
			chk(err)
			fmt.Println("Time", num, ":", float64(time.Now().UnixNano()-t)/1000000000)

			for j := 0; j < 3000; j++ {
				t = time.Now().UnixNano()
				_, err = ws.Write([]byte(req))
				chk(err)
				var msg = make([]byte, 5120)
				_, err := ws.Read(msg)
				chk(err)
				// fmt.Println(string(msg))
				if j%10 == 0 {
					ws, _ = websocket.Dial("wss://ws.binaryws.com/websockets/v3?app_id=1&l=EN", "", "http://load_test")
					fmt.Printf("[%d, %d] Received for : %d after %f\n", j, num, num, float64(time.Now().UnixNano()-t)/1000000000)
				}
				time.Sleep(time.Millisecond * 1100)
			}
		}(i)
	}

	time.Sleep(time.Second * 10000)
}
开发者ID:kavehmz,项目名称:garbage,代码行数:27,代码来源:binary_ws.go


示例2: TestAddClientRecive

func TestAddClientRecive(t *testing.T) {
	var server = GlobalIM
	var roomID = "master"
	server.Init()
	t.Log("add a room")
	server.Rm.Add(roomID)

	go func() {
		if err := http.ListenAndServe("localhost:9999", nil); err != nil {
			panic(err)
		}
	}()

	// let listen start.
	time.Sleep(2 * time.Second)

	ws1, err := websocket.Dial("ws://localhost:9999/im?room_id="+roomID+"&uname=1", "", "http://localhost:9999")
	if err != nil {
		t.Fatal(err)
	}

	ws2, err := websocket.Dial("ws://localhost:9999/im?room_id="+roomID+"&uname=2", "", "http://localhost:9999")
	if err != nil {
		t.Fatal(err)
	}
	ws3, err := websocket.Dial("ws://localhost:9999/im?room_id="+roomID+"&uname=3", "", "http://localhost:9999")
	if err != nil {
		t.Fatal(err)
	}
	m := &msg{
		Playload: "client1",
	}

	t.Log("will send.")
	if err := websocket.JSON.Send(ws1, m); err != nil {
		t.Fatal(err)
	} else {
		t.Log("has been send.")
	}

	m = new(msg)
	if err := websocket.JSON.Receive(ws2, m); err != nil {
		t.Fatal(err)
	}
	t.Log("Get message:", string(m.Playload))
	if err := websocket.JSON.Receive(ws3, m); err != nil {
		t.Fatal(err)
	}
	t.Log("Get message:", string(m.Playload))
	data, err := json.Marshal(m)
	if err != nil {
		t.Fatal(err)
	}
	t.Log("Json", string(data))

}
开发者ID:Alienero,项目名称:IamServer,代码行数:56,代码来源:im_test.go


示例3: Forever

func (this *Client) Forever(pattern string, route bool) (chan *jarvis.Event, error) {
	var process string
	if route {
		process = this.Process
	}
	ws, err := websocket.Dial("ws://"+this.Root+"/subscribe/forever?process="+process+"&pattern="+pattern, "", "http://jarvis")
	if err != nil {
		log.Println(err)
		return nil, err
	}
	result := make(chan *jarvis.Event)

	go func() {
		msg := make([]byte, 4096)
		for {
			n, err := ws.Read(msg)
			if err != nil {
				break
			}
			event := new(jarvis.Event)
			err = json.Unmarshal(msg[:n], &event)
			result <- event
		}
		close(result)
	}()

	return result, nil
}
开发者ID:ironbay,项目名称:jarvis-go,代码行数:28,代码来源:client.go


示例4: connect

func connect(userID string, clientID string) {
	ws, err := websocket.Dial(getServer(), "", "http://localhost/")
	if err != nil {
		Debug(err.Error())
		return
	}

	message := []byte(fmt.Sprintf("%s:%s", userID, clientID))
	_, err = ws.Write(message)
	if err != nil {
		Debug(err.Error())
		return
	}
	Debug(fmt.Sprintf("Sent: %s\n", message))

	for {
		var msg = make([]byte, 512)
		_, err = ws.Read(msg)
		if err != nil {
			Debug(err.Error())
			return
		}

		Debug(fmt.Sprintf("Received: %s\n", msg))

		CmdChan <- string(bytes.Trim(msg, "\x00"))
	}
}
开发者ID:mikeflynn,项目名称:echo-tunnel,代码行数:28,代码来源:main.go


示例5: TestEchoWithoutTestHelpers

func TestEchoWithoutTestHelpers(t *testing.T) {
	s := neptulon.NewServer("127.0.0.1:3002")
	go s.ListenAndServe()
	time.Sleep(time.Millisecond * 30)
	defer s.Close()

	s.MiddlewareFunc(func(ctx *neptulon.ReqCtx) error {
		t.Log("Request received:", ctx.Method)
		ctx.Res = "response-wow!"
		return ctx.Next()
	})

	origin := "http://127.0.0.1"
	url := "ws://127.0.0.1:3002"
	ws, err := websocket.Dial(url, "", origin)
	if err != nil {
		t.Fatal(err)
	}
	if err := websocket.JSON.Send(ws, map[string]string{"id": "123", "method": "test"}); err != nil {
		t.Fatal(err)
	}
	var res interface{}
	if err := websocket.JSON.Receive(ws, &res); err != nil {
		t.Fatal(err)
	}
	t.Log("Got response:", res)

	if err := ws.Close(); err != nil {
		t.Fatal(err)
	}

	time.Sleep(time.Millisecond * 30)
}
开发者ID:soygul,项目名称:neptulon,代码行数:33,代码来源:message_test.go


示例6: TestProxyUpgrade

func TestProxyUpgrade(t *testing.T) {
	backendServer := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {
		defer ws.Close()
		body := make([]byte, 5)
		ws.Read(body)
		ws.Write([]byte("hello " + string(body)))
	}))
	defer backendServer.Close()

	serverURL, _ := url.Parse(backendServer.URL)
	proxyHandler := &UpgradeAwareProxyHandler{
		Location: serverURL,
	}
	proxy := httptest.NewServer(proxyHandler)
	defer proxy.Close()

	ws, err := websocket.Dial("ws://"+proxy.Listener.Addr().String()+"/some/path", "", "http://127.0.0.1/")
	if err != nil {
		t.Fatalf("websocket dial err: %s", err)
	}
	defer ws.Close()

	if _, err := ws.Write([]byte("world")); err != nil {
		t.Fatalf("write err: %s", err)
	}

	response := make([]byte, 20)
	n, err := ws.Read(response)
	if err != nil {
		t.Fatalf("read err: %s", err)
	}
	if e, a := "hello world", string(response[0:n]); e != a {
		t.Fatalf("expected '%#v', got '%#v'", e, a)
	}
}
开发者ID:SivagnanamCiena,项目名称:calico-kubernetes,代码行数:35,代码来源:proxy_test.go


示例7: Start

func (c Client) Start() error {
	ws, err := websocket.Dial(c.url(), "", c.originUrl())
	if err != nil {
		return err
	}

	chat := chat_sample_view.NewChatView("CHAT>")
	chat.EnterAction = func(text string) {
		msg := Message{Name: c.Name, Text: text}
		data, _ := json.Marshal(msg)
		ws.Write(data)
	}

	chat.Init()
	defer chat.Close()

	go func() {
		for {
			rcv := make([]byte, 512)
			n, _ := ws.Read(rcv)
			var msg Message
			json.Unmarshal(rcv[0:n], &msg)
			chat.Message(&msg)
		}
	}()

	chat.Draw()
	chat.PollInput()

	return nil
}
开发者ID:monochromegane,项目名称:chat_sample,代码行数:31,代码来源:client.go


示例8: Connect

// Connect trys to connect the bot to the slack channel via token. It also stores the initial state of the slack.
func (b *Bot) Connect(token string) error {
	c := &http.Client{}
	resp, err := c.Get("https://slack.com/api/rtm.start?token=" + token)
	if err != nil {
		return err
	}
	dec := json.NewDecoder(resp.Body)
	var val rtmStart
	if err := dec.Decode(&val); err != nil {
		return err
	}
	resp.Body.Close()
	u, err := url.Parse(val.URL)
	if err != nil {
		return err
	}
	u.Host += ":443"
	conn, err := websocket.Dial(u.String(), "", "https://slack.com")
	if err != nil {
		return err
	}
	b.Channels = val.Channels
	b.Conn = conn
	b.Users = val.Users
	b.Self = val.Self
	b.Team = val.Team
	return nil
}
开发者ID:foolusion,项目名称:slackbot,代码行数:29,代码来源:slackbot.go


示例9: TestWebSocket_Query

func TestWebSocket_Query(t *testing.T) {
	mux := http.NewServeMux()
	h := Handler{Tx: newTransceiver()}
	<-h.Register(mux)
	s := httptest.NewServer(mux)
	defer s.Close()
	url := strings.Replace(s.URL, "http:", "ws:", 1)
	ws, err := websocket.Dial(url+"/v1/ws/jsonrpc", "", "http://localhost")
	if err != nil {
		t.Fatal(err)
	}
	defer ws.Close()
	cli := rpc.NewClientWithCodec(jsonrpc.NewClientCodec(ws))
	args := &QueryMessage{
		Src:       "nobody",
		MessageID: "foobar",
	}
	var resp QueryMessageResp
	err = cli.Call("SM.Query", args, &resp)
	if err != nil {
		t.Fatal(err)
	}
	want := "DELIVERED"
	if resp.MsgState != want {
		t.Fatalf("unexpected message state: want %q, have %q",
			want, resp.MsgState)
	}
}
开发者ID:fiorix,项目名称:sms-api-server,代码行数:28,代码来源:http_test.go


示例10: newWSProxy

// newWSProxy returns a websocket handler which forwards
// messages from an incoming WS connection to an outgoing
// WS connection. It builds upon the golang.org/x/net/websocket
// library for both incoming and outgoing connections.
func newWSProxy(t *url.URL) http.Handler {
	return websocket.Handler(func(in *websocket.Conn) {
		defer in.Close()

		r := in.Request()
		targetURL := "ws://" + t.Host + r.RequestURI
		out, err := websocket.Dial(targetURL, "", r.Header.Get("Origin"))
		if err != nil {
			log.Printf("[INFO] WS error for %s. %s", r.URL, err)
			return
		}
		defer out.Close()

		errc := make(chan error, 2)
		cp := func(dst io.Writer, src io.Reader) {
			_, err := io.Copy(dst, src)
			errc <- err
		}

		go cp(out, in)
		go cp(in, out)
		err = <-errc
		if err != nil && err != io.EOF {
			log.Printf("[INFO] WS error for %s. %s", r.URL, err)
		}
	})
}
开发者ID:r0p0s3c,项目名称:fabio,代码行数:31,代码来源:ws.go


示例11: Connect

func (m *MatlabSession) Connect() {

	origin := "http://localhost/"
	url := "ws://localhost:9999/matsock"
	// url = "ws://localhost:12345/echo"
	var err error
	m.matlabshell, err = websocket.Dial(url, "", origin)

	if err != nil {
		log.Fatal(err)
	}
	// Say hello to the matlab shell

	// n, err := m.matlabshell.Write([]byte("Matlab Connecting... !"))

	// log.Printf("Wrote %d writing Error %v ", n, err)
	// var msg = make([]byte, 512)
	// if n, err = m.matlabshell.Read(msg); err != nil {
	// 	log.Fatal(err)
	// }
	// fmt.Printf("Received: %s.\n", msg[:n])
	// var msg = make([]byte, 512)
	// var n int
	// if n, err = ws.Read(msg); err != nil {
	// 	log.Fatal(err)
	// }
	// fmt.Printf("Received: %s.\n", msg[:n])

	// m.matlabshell=
}
开发者ID:wiless,项目名称:webplot,代码行数:30,代码来源:webmatlab.go


示例12: main

func main() {
	var url, origin string
	flag.StringVar(&url, "url", "ws://127.0.0.1:9999/echo", "websocket URL")
	flag.StringVar(&origin, "origin", "http://localhost/", "origin header")
	flag.Parse()

	if url == "" {
		flag.Usage()
		os.Exit(1)
	}

	ws, err := websocket.Dial(url, "", origin)
	if err != nil {
		log.Fatal(err)
	}

	go func() {
		var msg = make([]byte, 512)
		for {
			n, err := ws.Read(msg)
			if err != nil {
				log.Fatal(err)
			}
			fmt.Printf("R: %s\nS: ", msg[:n])
		}
	}()

	fmt.Print("S: ")
	sc := bufio.NewScanner(os.Stdin)
	for sc.Scan() {
		if _, err := ws.Write(sc.Bytes()); err != nil {
			log.Fatal(err)
		}
	}
}
开发者ID:cursesun,项目名称:fabio,代码行数:35,代码来源:wsclient.go


示例13: connect

// connect logs on user. Blocks until successfull and
// returns the websocket connection
func connect(hostWS, username string, client int) (conn *websocket.Conn) {
	// Request Mycel server to log in
	for {
		var err error
		conn, err = websocket.Dial(fmt.Sprintf("%s/subscribe/clients/%d", hostWS, client), "", "http://localhost")
		if err != nil {
			fmt.Println("Can't connect to Mycel websocket server. Trying reconnect in 1 second...")
			time.Sleep(1 * time.Second)
			continue
		}
		break
	}
	// Create and send log-on request
	logonMsg := logOnOffMessage{Action: "log-on", Client: client, User: username}
	err := websocket.JSON.Send(conn, logonMsg)
	if err != nil {
		fmt.Println("Couldn't send message " + err.Error())
	}
	// Wait for "logged-on" confirmation
	var msg message
	for {
		err := websocket.JSON.Receive(conn, &msg)
		if err != nil {
			if err == io.EOF {
				break
			}
			fmt.Println("Couldn't receive msg " + err.Error())
		}

		if msg.Status == "logged-on" {
			break
		}
	}
	return
}
开发者ID:digibib,项目名称:mycel-client,代码行数:37,代码来源:client.go


示例14: newWSConnection

func (conn *Connection) newWSConnection() (*websocket.Conn, error) {
	resp, err := http.PostForm(
		"https://slack.com/api/rtm.start",
		url.Values{"token": {conn.token}},
	)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var r RTMStart
	err = json.NewDecoder(resp.Body).Decode(&r)
	if err != nil {
		return nil, err
	}

	conn.userId = r.Self.Id
	conn.userName = r.Self.Name
	conn.domain = r.Team.Domain

	conn.userMap = map[string]string{}
	conn.channelMap = map[string]string{}
	for _, v := range r.Users {
		conn.userMap[v.Id] = v.Name
	}
	for _, v := range r.Channels {
		conn.channelMap[v.Id] = v.Name
	}

	return websocket.Dial(r.Url, "", "https://slack.com/")
}
开发者ID:mix3,项目名称:guiniol,代码行数:31,代码来源:connection.go


示例15: reconnect

func reconnect(origin, deviceId, channelId, endpoint string) (err error) {
	socket, err := ws.Dial(origin, "", origin)
	if err != nil {
		return fmt.Errorf("Error dialing origin: %s", err)
	}
	connId, err := id.Generate()
	if err != nil {
		return fmt.Errorf("Error generating connection ID: %#v", err)
	}
	conn := client.NewConn(socket, connId, true)
	defer conn.Close()
	defer conn.Purge()
	actualId, err := conn.WriteHelo(deviceId, channelId)
	if err != nil {
		return fmt.Errorf("Error writing handshake request: %s", err)
	}
	if actualId != deviceId {
		return fmt.Errorf("Mismatched device IDs: got %q; want %q",
			actualId, deviceId)
	}
	if err = roundTrip(conn, deviceId, channelId, endpoint, 2); err != nil {
		return fmt.Errorf("Error sending notification after reconnect: %s", err)
	}
	return nil
}
开发者ID:jrconlin,项目名称:pushgo,代码行数:25,代码来源:smoke_test.go


示例16: Listen

func (c *client) Listen(cancel chan struct{}) error {
	if c.ws != nil {
		return fmt.Errorf("already listening")
	}

	url, err := c.websocketURL()
	if err != nil {
		return err
	}
	c.ws, err = websocket.Dial(url, "", "http://localhost")
	if err != nil {
		return fmt.Errorf("error dialing: %v", err)
	}

	ch := make(chan []byte)
	for {
		go c.read(ch)
		select {
		case b := <-ch:
			var e event
			if err := json.Unmarshal(b, &e); err != nil {
				log.Printf("Error unmarshaling websocket type: %v", err)
			}
			switch e.Type {
			case "hello":
				var h Hello
				if err := json.Unmarshal(b, &h); err != nil {
					log.Printf("Error unmarshaling websocket response: %v", err)
				}
				if len(c.helloHandlers) == 0 {
					log.Printf("No listeners for hello events")
				}
				for _, c := range c.helloHandlers {
					c(h)
				}
			case "message":
				var m Message
				if err := json.Unmarshal(b, &m); err != nil {
					log.Printf("Error unmarshaling websocket response: %v", err)
				}
				c.echoSuppresser.Wait()
				if !c.messageFilter(&m) || c.echoSuppresser.WasSent(m.TS) {
					log.Printf("Skipping filtered message: %v", m)
					continue
				}
				if len(c.messageHandlers) == 0 {
					log.Printf("No listeners for message events")
				}
				for _, c := range c.messageHandlers {
					c(m)
				}
			default:
				log.Printf("Ignoring unknown event: %q", string(b))
			}
		case _ = <-cancel:
			return c.ws.Close()
		}
	}
	return nil
}
开发者ID:illicitonion,项目名称:slackbridge,代码行数:60,代码来源:websocket.go


示例17: NewClient

// NewClient creates a default client (using an internal websocket) to the
// provided URL using the origin for the connection. The client will
// automatically connect, upgrade to a websocket, and establish a DDP
// connection session before returning the client. The client will
// automatically and internally handle heartbeats and reconnects.
//
// TBD create an option to use an external websocket (aka htt.Transport)
// TBD create an option to substitute heartbeat and reconnect behavior (aka http.Tranport)
// TBD create an option to hijack the connection (aka http.Hijacker)
// TBD create profiling features (aka net/http/pprof)
func NewClient(url, origin string) (*Client, error) {
	ws, err := websocket.Dial(url, "", origin)
	if err != nil {
		return nil, err
	}
	c := &Client{
		HeartbeatInterval: 45 * time.Second, // Meteor impl default + 10 (we ping last)
		HeartbeatTimeout:  15 * time.Second, // Meteor impl default
		ReconnectInterval: 5 * time.Second,
		collections:       map[string]Collection{},
		ws:                ws,
		url:               url,
		origin:            origin,
		inbox:             make(chan map[string]interface{}, 100),
		errors:            make(chan error, 100),
		pings:             map[string][]*pingTracker{},
		calls:             map[string]*Call{},
		subs:              map[string]*Call{},

		idManager: *newidManager(),
	}

	// We spin off an inbox processing goroutine
	go c.inboxManager()

	// Start DDP connection
	c.start(ws, NewConnect())

	return c, nil
}
开发者ID:gchpaco,项目名称:ddp,代码行数:40,代码来源:ddp_client.go


示例18: connect

func (s *Slack) connect() {
	token := s.config.Slack.Token
	url := fmt.Sprintf("https://slack.com/api/rtm.start?token=%s", token)
	resp, err := http.Get(url)
	if err != nil {
		return
	}
	if resp.StatusCode != 200 {
		log.Fatalf("Slack API failed. Code: %d", resp.StatusCode)
	}
	body, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		log.Fatalf("Error reading Slack API body: %s", err)
	}
	var rtm rtmStart
	err = json.Unmarshal(body, &rtm)
	if err != nil {
		return
	}

	if !rtm.Ok {
		log.Fatalf("Slack error: %s", rtm.Error)
	}

	s.url = "https://slack.com/api/"
	s.id = rtm.Self.Id

	s.ws, err = websocket.Dial(rtm.Url, "", s.url)
	if err != nil {
		log.Fatal(err)
	}
}
开发者ID:chrissexton,项目名称:catbase,代码行数:33,代码来源:slack.go


示例19: Test_websocket_should_push_notification

func Test_websocket_should_push_notification(t *testing.T) {
	// given
	mux := http.NewServeMux()
	notifChan := web.SetupWebsocket(mux)
	srv := httptest.NewServer(mux)
	defer srv.Close()
	// and
	ws, err := websocket.Dial(strings.Replace(srv.URL, "http", "ws", 1)+"/websocket", "", srv.URL)
	if err != nil {
		t.Fatal(err.Error())
	}
	// then
	go func() {
		// when
		notifChan <- commons.Notification{PlayerId: "playerId", Type: commons.Registrate}
		time.Sleep(time.Second * 5)
		ws.Close()
	}()
	var notif commons.Notification
	var data []byte
	data, _ = ioutil.ReadAll(ws) //todo not the right func !
	ws.Close()
	json.Unmarshal(data, &notif)
	assert.Equal(t, "playerId", notif.PlayerId)
	assert.Equal(t, commons.Registrate, notif.Type)
}
开发者ID:vil-coyote-acme,项目名称:go-concurrency,代码行数:26,代码来源:websocket_blackbox_test.go


示例20: HandleIncomingEvents

func (api *WS) HandleIncomingEvents(ch chan SlackEvent) {
	for {
		event := json.RawMessage{}
		if err := websocket.JSON.Receive(api.conn, &event); err == io.EOF {
			//log.Println("Derpi derp, should we destroy conn and start over?")
			//if err = api.StartRTM(); err != nil {
			//	log.Fatal(err)
			//}
			// should we reconnect here?
			if !api.conn.IsClientConn() {
				api.conn, err = websocket.Dial(api.info.URL, api.config.protocol, api.config.origin)
				if err != nil {
					log.Panic(err)
				}
			}
			// XXX: check for timeout and implement exponential backoff
		} else if err != nil {
			log.Panic(err)
		}
		if len(event) == 0 {
			if api.debug {
				log.Println("Event Empty. WTF?")
			}
		} else {
			if api.debug {
				log.Println(string(event[:]))
			}
			api.handleEvent(ch, event)
		}
		time.Sleep(time.Millisecond * 500)
	}
}
开发者ID:ciscou,项目名称:slack,代码行数:32,代码来源:websocket.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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