Example #1
0
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)
}
Example #2
0
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))

}
Example #3
0
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
}
Example #4
0
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"))
	}
}
Example #5
0
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)
}
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)
	}
}
Example #7
0
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
}
Example #8
0
// 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
}
Example #9
0
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)
	}
}
Example #10
0
File: ws.go Project: r0p0s3c/fabio
// 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)
		}
	})
}
Example #11
0
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=
}
Example #12
0
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)
		}
	}
}
Example #13
0
// 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
}
Example #14
0
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/")
}
Example #15
0
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
}
Example #16
0
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
}
Example #17
0
// 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
}
Example #18
0
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)
	}
}
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)
}
Example #20
0
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)
	}
}
Example #21
0
func TestWebSocket_Send(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 := &ShortMessage{
		Dst:  "root",
		Text: "hello world",
	}
	var resp ShortMessageResp
	err = cli.Call("SM.Submit", args, &resp)
	if err != nil {
		t.Fatal(err)
	}
	want := "foobar"
	if resp.MessageID != want {
		t.Fatalf("unexpected message id: want %q, have %q",
			want, resp.MessageID)
	}
}
Example #22
0
func (api *Slack) StartRTM(protocol, origin string) (*WS, error) {
	response := &infoResponseFull{}
	err := parseResponse("rtm.start", url.Values{"token": {api.config.token}}, response, api.debug)
	if err != nil {
		return nil, err
	}
	if !response.Ok {
		return nil, response.Error
	}
	api.info = response.Info
	// websocket.Dial does not accept url without the port (yet)
	// Fixed by: https://github.com/golang/net/commit/5058c78c3627b31e484a81463acd51c7cecc06f3
	// but slack returns the address with no port, so we have to fix it
	api.info.URL, err = fixURLPort(api.info.URL)
	if err != nil {
		return nil, err
	}
	api.config.protocol, api.config.origin = protocol, origin
	wsAPI := &WS{Slack: *api}
	wsAPI.conn, err = websocket.Dial(api.info.URL, api.config.protocol, api.config.origin)
	if err != nil {
		return nil, err
	}
	wsAPI.pings = make(map[int]time.Time)
	return wsAPI, nil
}
Example #23
0
func TestWebsockets(t *testing.T) {
	l := New()
	l.WebSocket("/ws", func(c Context) {

		recv := make([]byte, 1000)

		i, err := c.WebSocket().Read(recv)
		if err == nil {
			c.WebSocket().Write(recv[:i])
		}
	})

	server := httptest.NewServer(l.Serve())
	defer server.Close()

	addr := server.Listener.Addr().String()
	origin := "http://localhost"

	url := fmt.Sprintf("ws://%s/ws", addr)
	ws, err := websocket.Dial(url, "", origin)
	Equal(t, err, nil)

	defer ws.Close()

	ws.Write([]byte("websockets in action!"))

	buf := new(bytes.Buffer)
	buf.ReadFrom(ws)

	Equal(t, "websockets in action!", buf.String())
}
Example #24
0
func DialOrigin(origin string) (*Conn, error) {
	socket, err := ws.Dial(origin, "", origin)
	if err != nil {
		return nil, err
	}
	return NewConn(socket, false), nil
}
Example #25
0
func (con *Connection) newWSConnection() (*websocket.Conn, error) {
	resp, err := http.PostForm("https://slack.com/api/rtm.start", url.Values{"token": {con.token}})
	if err != nil {
		return nil, err
	}

	var r struct {
		Ok    bool   `json:"ok"`
		Url   string `json:"url"`
		Error string `json:"error"`
		Self  struct {
			Id   string `json:"id"`
			Name string `json:"name"`
		} `json:"self"`
		Users []struct {
			Id   string `json:"id"`
			Name string `json:"name"`
		} `json:"users"`
	}

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

	con.userId = r.Self.Id
	con.userName = r.Self.Name
	userMap := map[string]string{}
	for _, user := range r.Users {
		userMap[user.Id] = user.Name
	}
	con.userMap = userMap

	return websocket.Dial(r.Url, "", "https://slack.com/")
}
Example #26
0
// Tests runtime information support
func TestRuntimeGetRuntime(t *testing.T) {
	ensureRuntimeStarted()
	// Create a WebSocket client
	ws, err := websocket.Dial("ws://localhost:13014/", "", "http://localhost/")
	if err != nil {
		t.Error(err.Error())
	}
	// Send a runtime request and check the response
	if err = websocket.JSON.Send(ws, &Message{"runtime", "getruntime", nil}); err != nil {
		t.Error(err.Error())
	}
	var msg runtimeMessage
	if err = websocket.JSON.Receive(ws, &msg); err != nil {
		t.Error(err.Error())
		return
	}
	if msg.Protocol != "runtime" || msg.Command != "runtime" {
		t.Errorf("Invalid protocol (%s) or command (%s)", msg.Protocol, msg.Command)
		return
	}
	res := msg.Payload
	if res.Type != "goflow" {
		t.Errorf("Invalid protocol type: %s\n", res.Type)
	}
	if res.Version != "0.4" {
		t.Errorf("Invalid protocol version: %s\n", res.Version)
	}
	if len(res.Capabilities) != 5 {
		t.Errorf("Invalid number of supported capabilities: %v\n", res.Capabilities)
	}
	if res.Id == "" {
		t.Error("Runtime Id is empty")
	}
}
Example #27
0
func dialWebsocket(db *sql.DB, wg *sync.WaitGroup, i int) {

	origin := "http://localhost/"
	url := "ws://localhost:8080/scoreboard"

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

	res, err := scoreboard.CollectLastResult(db)
	if err != nil {
		log.Fatal(err)
	}

	html_res := res.ToHTML(false)

	var msg = make([]byte, len(html_res))
	if _, err = ws.Read(msg); err != nil {
		log.Fatal(err)
	}

	if string(msg) != html_res {
		log.Fatalln("Received result invalid",
			html_res, msg)
	}

	wg.Done()
}
Example #28
0
func (w *myWorker) Setup() {
	conn, err := websocket.Dial(w.url, "", w.origin)
	if err != nil {
		log.Fatal(err)
	}
	w.conn = conn
}
Example #29
0
File: cli.go Project: morikuni/weso
// NewCLI create CLI from Config.
func NewCLI(conf *Config) (*CLI, error) {
	origin := "http://127.0.0.1"
	if conf.Origin != "" {
		origin = conf.Origin
	}
	conn, err := websocket.Dial(conf.URL, "", origin)
	if err != nil {
		return nil, err
	}
	template := EmptyTemplate
	if _, err := os.Stat(conf.Template); err == nil {
		template, err = NewTemplateFile(conf.Template)
		if err != nil {
			return nil, err
		}
	}

	cli := &CLI{
		conn,
		liner.NewLiner(),
		template,
		conf.Debug,
	}

	cli.liner.SetCtrlCAborts(true)
	cli.liner.SetCompleter(Completer(template))

	return cli, nil
}
Example #30
0
func TestWebSocket_Deliver(t *testing.T) {
	mux := http.NewServeMux()
	h := Handler{Tx: &smpp.Transceiver{Addr: ":0"}}
	<-h.Register(mux)
	s := httptest.NewServer(mux)
	defer s.Close()
	u := strings.Replace(s.URL, "http:", "ws:", 1)
	ws, err := websocket.Dial(u+"/v1/ws/jsonrpc/events", "", "http://localhost")
	if err != nil {
		t.Fatal(err)
	}
	defer ws.Close()
	h.pool.Broadcast(&DeliveryReceipt{
		Src:  "bart",
		Dst:  "lisa",
		Text: "delivery receipt here",
	})
	srv := rpc.NewServer()
	NewSM(h.Tx, srv)
	go func() {
		deliverErr <- srv.ServeRequest(jsonrpc.NewServerCodec(ws))
	}()
	select {
	case err = <-deliverErr:
		if err != nil {
			t.Fatal(err)
		}
	case <-time.After(2 * time.Second):
		t.Fatal("timeout waiting for delivery receipt")
	}
}