コード例 #1
0
func doConnect(cservAddr string, gameServHostPort string) (*websocket.Conn, error) {
	if gameServHostPort == "" {
		// Get server addr from central server
		isReady := false
		hostport := ""
		for !isReady {
			resp, err := http.Get(cservAddr)
			if err != nil {
				LOGV.Println("Could not connect to central server.")
				return nil, err
			}
			data, err := ioutil.ReadAll(resp.Body)
			resp.Body.Close()
			if err != nil {
				LOGV.Println("Your mother phat")
				return nil, err
			}
			LOGV.Println("received data from cserv")
			unpacked := &centralserver.HttpReply{}
			err = json.Unmarshal(data, &unpacked)
			if err != nil {
				LOGV.Println("Your mother phat")
				return nil, err
			}
			isReady = unpacked.Status == "OK"
			if isReady {
				hostport = unpacked.Hostport
				gameServHostPort = hostport
				// Connect to the server
				origin := "http://localhost/"
				url := "ws://" + gameServHostPort + "/abc"
				ws, err := websocket.Dial(url, "", origin)
				if err != nil {
					LOGV.Println("Could not open websocket connection to server")
					isReady = false
				} else {
					LOGE.Println("Connection has been established with server " + gameServHostPort)
					return ws, nil
				}
			}
			time.Sleep(250 * time.Millisecond)
		}
	}

	// Connect to the server
	origin := "http://localhost/"
	url := "ws://" + gameServHostPort + "/abc"
	ws, err := websocket.Dial(url, "", origin)
	if err != nil {
		LOGV.Println("Could not open websocket connection to server")
		return nil, err
	} else {
		LOGE.Println("Connection has been established with server " + gameServHostPort)
		return ws, nil
	}
}
コード例 #2
0
ファイル: rootH.go プロジェクト: nandopeters/goplay
func main() {

	var cfgFile = "msgsrvr.cfg"
	HOST, PORT, errFile := configfile.GetHostPort(cfgFile)
	if errFile != nil {
		fmt.Println(errFile.Error())
		fmt.Println("Unable to read configuration from file :" + cfgFile)
		return
	}

	service := "ws://" + HOST + ":" + PORT

	if len(os.Args) > 1 {
		service += "/" + os.Args[1]
	} else {
		service += "/"
	}

	//Connect
	conn, err := websocket.Dial(service, "", "http://"+HOST)
	checkError(err)

	//Send
	smsg := locationUpdate()
	err = websocket.Message.Send(conn, smsg)
	checkError(err)

	//Receive
	var rmsg string
	err = websocket.Message.Receive(conn, &rmsg)
	checkError(err)
	fmt.Println("Received: " + rmsg)

	os.Exit(0)
}
コード例 #3
0
ファイル: wsclient.go プロジェクト: foamdino/learning-go
func main() {
	if len(os.Args) != 2 {
		fmt.Println("Usage: ", os.Args[0], "ws://host:port")
		os.Exit(1)
	}

	service := os.Args[1]
	con, err := websocket.Dial(service, "", "http://localhost")
	checkErr(err)

	var msg string
	for {
		err := websocket.Message.Receive(con, &msg)
		if err != nil {
			if err == io.EOF {
				break
			}
			fmt.Println("Couldn't receive message: ", err.Error())
			break
		}

		fmt.Println("Received from server: ", msg)

		err = websocket.Message.Send(con, msg)
		if err != nil {
			fmt.Println("Couldn't return message")
			break
		}
	}
	os.Exit(0)
}
コード例 #4
0
ファイル: pound.go プロジェクト: jrconlin/go_pound
func poundSock(target string, config *Config, cmd, ctrl chan int, id int) (err error) {
	defer func() {
		if r := recover(); r != nil {
			log.Printf(".")
		}
	}()
	hostname := os.Getenv("HOST")
	if hostname == "" {
		hostname = "localhost"
	}
	targ := target // + fmt.Sprintf("#id=%d", id)
	log.Printf("INFO : (%d) Connecting from %s to %s\n", id,
		"ws://"+hostname, targ)
	//ws, err := websocket.Dial(targ, "push-notification", targ)
	ws, err := websocket.Dial(targ, "", targ)
	err = ws.SetDeadline(time.Now().Add(time.Second * 30))
	if err != nil {
		log.Printf("ERROR: (%d) Unable to open websocket: %s\n",
			id, err.Error())
		cmd <- id
		return err
	}
	duration, err := time.ParseDuration(config.Sleep)
	tc := time.NewTicker(duration)
	msg := fmt.Sprintf("{\"messageType\": \"hello\", "+
		"\"uaid\": \"%s\", \"channelIDs\":[]}", genToken())
	_, err = ws.Write([]byte(msg))
	websocket.Message.Receive(ws, &msg)
	for {
		err = ws.SetDeadline(time.Now().Add(time.Second * 5))
		if err != nil {
			log.Printf("ERROR: (%d) Unable to write ping to websocket %s\n",
				id, err.Error())
			cmd <- id
			return err
		}
		ws.Write([]byte("{}"))
		// do a raw receive from the socket.
		// Note: ws.Read doesn't like pulling data.
		var msg string
		websocket.Message.Receive(ws, &msg)

		//if _, err = ws.Read(msg); err != nil {
		//
		//	log.Printf("WARN : (%d) Bad response %s\n", id, err)
		//	cmd <- id
		//	return
		//}
		select {
		case cc := <-ctrl:
			if cc == 0 {
				break
			}
		case <-tc.C:
			continue
		}
	}
	log.Printf("INFO : (%d) Shutting down...\n", id)
	return err
}
コード例 #5
0
func handleConnection(conn *net.TCPConn) error {
	defer conn.Close()

	handlerChan <- 1
	defer func() {
		handlerChan <- -1
	}()

	var ws *websocket.Conn

	conn.SetDeadline(time.Now().Add(socksTimeout))
	err := AwaitSocks4aConnect(conn, func(dest string) (*net.TCPAddr, error) {
		// Disable deadline.
		conn.SetDeadline(time.Time{})
		Log("SOCKS request for %s", dest)
		destAddr, err := net.ResolveTCPAddr("tcp", dest)
		if err != nil {
			return nil, err
		}
		wsUrl := url.URL{Scheme: "ws", Host: dest}
		ws, err = websocket.Dial(wsUrl.String(), "", wsUrl.String())
		if err != nil {
			return nil, err
		}
		Log("WebSocket connection to %s", ws.Config().Location.String())
		return destAddr, nil
	})
	if err != nil {
		return err
	}
	defer ws.Close()
	proxy(conn, ws)
	return nil
}
コード例 #6
0
ファイル: cf_sink_test.go プロジェクト: shageman/loggregator
func TestThatItSends(t *testing.T) {
	receivedChan := make(chan []byte, 2)

	expectedData := "Some Data"
	otherData := "More stuff"

	ws, err := websocket.Dial("ws://localhost:8080/tail", "string", "http://localhost")
	assert.NoError(t, err)
	defer ws.Close()

	go func() {
		for {
			var data []byte
			err := websocket.Message.Receive(ws, &data)
			if err != nil {
				break
			}
			receivedChan <- data
		}
	}()

	dataReadChannel <- []byte(expectedData)
	dataReadChannel <- []byte(otherData)

	received := <-receivedChan
	assert.Equal(t, expectedData, string(received))

	receivedAgain := <-receivedChan
	assert.Equal(t, otherData, string(receivedAgain))
}
コード例 #7
0
func main() {
	fmt.Printf(`Welcome chatroom!
author: dotcoo zhao
url: http://www.dotcoo.com/golang-websocket-chatroom
        
`)

	origin := "http://127.0.0.1:6611/"
	url := "ws://127.0.0.1:6611/chatroom"

	ws, err := websocket.Dial(url, "", origin)
	if err != nil {
		panic(err)
	}
	defer ws.Close()

	r := bufio.NewReader(ws)
	//w := bufio.NewWriter(os.Stdout)

	go Command(ws)

	for {
		data, err := r.ReadBytes('\n')
		if err == io.EOF {
			fmt.Printf("disconnected\n")
			os.Exit(0)
		}
		if err != nil {
			panic(err)
		}

		fmt.Printf("\r%sMy\t> ", data)
	}
}
コード例 #8
0
func TestWebsocketHandlerJSON(t *testing.T) {
	once.Do(startServer)

	ws, err := websocket.Dial(fmt.Sprintf("ws://%s/json", serverAddr), "", "http://localhost/")
	if err != nil {
		t.Fatal("dialing", err)
	}

	input := []byte("hello")
	if _, err := ws.Write(input); err != nil {
		t.Errorf("Write: %v", err)
	}
	var output = make([]byte, 1024)
	n, err := ws.Read(output)
	if err != nil {
		t.Errorf("Read: %v", err)
	}
	output = output[0:n]

	actual_output := []byte(c.ParseToSentence(string(input)).ToJSON())

	if !bytes.Equal(output, actual_output) {
		t.Errorf("Echo: expected %q got %q", actual_output, output)
	}
}
コード例 #9
0
ファイル: gopush_test.go プロジェクト: Pronovix/gopush
func testNotificationWithWebsocket(key *rsa.PrivateKey, t *testing.T, centername string, shouldSucceed bool) {
	// Connect to host with websockets
	wsconn, err := websocket.Dial(getRawPath("listen?center="+getCenterName("*****@*****.**", centername), "ws"), "", getPath(""))
	if err != nil {
		t.Fatal(err)
	}

	testmsg := testNotificationSending(key, t, centername, shouldSucceed)

	// The buffer needs to be bigger than the message, to make sure that a longer message won't get mistaken to the original.
	// For example if the test message is "aaa" and the result would be "aaab"
	buf := make([]byte, len(testmsg)+1)
	n, err := wsconn.Read(buf)
	if err != nil {
		t.Fatal(err)
	}

	wsconn.Close()

	// The buffer is bigger, and the trailing bytes are not needed.
	result := string(buf[:n])

	if testmsg != result {
		t.Fatalf("Message retrieval through websocket is failed. Expected: '%s', got: '%s'\n", testmsg, result)
	}
}
コード例 #10
0
ファイル: connection.go プロジェクト: univedo/univedo-go
// Dial opens a new connection with an univedo server
func Dial(url string) (*Connection, error) {
	// Extract the origin from the URL
	origin, err := originForURL(url)
	if err != nil {
		return nil, err
	}

	// Dial the websocket
	if !strings.HasSuffix(url, "/") {
		url += "/"
	}

	url += "v1"
	ws, err := websocket.Dial(url, "", origin)
	if err != nil {
		return nil, err
	}

	c := &Connection{ws: ws, remoteObjects: make(map[uint64]RemoteObject)}
	go func() {
		// TODO error handling
		err := c.handleWebsocket()
		/*		fmt.Printf("%s\n", err.Error())*/
		_ = err
	}()

	// Login
	c.urologin = NewBasicRO(0, c)
	c.remoteObjects[0] = c.urologin

	return c, nil
}
コード例 #11
0
ファイル: client.go プロジェクト: tenntenn/netchan
// Importing channel from websocket sever.
func (cnn *clientConn) Connect(ch interface{}, name []byte) (errCh <-chan error) {
	errSender := make(chan error)
	errCh = errSender // read only
	defer func() {
		if r := recover(); r != nil {
			switch r.(type) {
			default:
				errSender <- fmt.Errorf("Error: %v", r)
			case error:
				err := r.(error)
				errSender <- err
			}
		}
	}()

	chpv := valueChan(ch)

	encodedName := base64.URLEncoding.EncodeToString(name)
	url := fmt.Sprintf("%s/%s", cnn.urlBase, encodedName)
	ws, err := websocket.Dial(url, "", cnn.origin)
	if err != nil {
		panic(err)
	}

	go func() {
		for {
			if v, ok := chpv.Recv(); ok {
				cnn.codec.Send(ws, v)
			}
		}
	}()

	return
}
コード例 #12
0
func TestStreamService(t *testing.T) {
	area, user := au.gen()
	//area, user := Area{"streamServiceArea"}, User{"superuser"}

	msgs := []Message{*area.joinMsg(user), Message{user, "testmsg"}}
	mch := make(chan string, 2)

	cAddr, err := ss.InitiateStream(area, user)
	if err != nil {
		t.Error("Error on InitiateStream!", err)
	}
	defer ss.CloseStream(area, user)

	client, err := websocket.Dial(cAddr, "", "http://localhost:21235/")
	if err != nil {
		t.Error("Error on opening return websocket!", err)
	}
	defer client.Close()

	go func() {
		for {
			var msg string
			err := websocket.Message.Receive(client, &msg)
			if err != nil {
				log.Println("Error receiving messages", err)
				break
			}
			mch <- msg
		}
		close(mch)
	}()

	// Send a message
	err = websocket.Message.Send(client, "{\"msg\":\"testmsg\"}")
	if err != nil {
		t.Error("Error on sending message through client websocket!")
	}

	select {
	case usermsg := <-mch:
		if usermsg != newStreamUserMessage(user, true).String() {
			t.Fatalf("User message isn't what was expected! (exp:%s) (msg:%s)",
				user.String(), usermsg)
		}
	case <-time.After(time.Second / 2):
		t.Fatal("No messages received after timeout!")
	}

	for j := range msgs {
		select {
		case msg := <-mch:
			if msg != newStreamChatMessage(&msgs[j]).String() {
				t.Errorf("Message isn't what was expected! Exp: %s, Actual: %s", msgs[j].String(), msg)
			}
		case <-time.After(time.Second):
			t.Error("No messages received after timeout!", j)
		}
	}

}
コード例 #13
0
ファイル: wsbench.go プロジェクト: yml/wsbench
// CreateWSConn Creates a new websocket connection
func CreateWsConn() (conn *websocket.Conn) {
	conn, err := websocket.Dial(Url, "", Origin)
	if err != nil {
		fmt.Println("Ooups!! I cannot create the websocket conn")
	}
	return
}
コード例 #14
0
ファイル: main.go プロジェクト: kazuroka/chat
func checkNames(serverurl, origin string, shouldrestart chan bool) {
	ws, err := websocket.Dial(serverurl, "", origin)
	if err != nil {
		P("Unable to connect to ", serverurl)
		shouldrestart <- true
		return
	}

	defer ws.Close()
	buff := make([]byte, 512)
	start := time.Now()

checknamesagain:
	ws.SetReadDeadline(time.Now().Add(time.Second))
	_, err = ws.Read(buff)
	if err != nil {
		P("Unable to read from the websocket ", err)
		shouldrestart <- true
		return
	}

	if time.Since(start) > 500*time.Millisecond {
		P("Didnt receive NAMES in 500ms, restarting")
		shouldrestart <- true
		return
	}

	if string(buff[:5]) != "NAMES" {
		goto checknamesagain
	}

}
コード例 #15
0
ファイル: websocket.go プロジェクト: ming-hai/appmsgsrv
func NewRemoveConn(pid int, userId string) {

	for {
		count := rand.Intn(5) + 1
		origin := "http://localhost/"
		url := "ws://10.180.120.63:6968/sub?key=" + userId + "_Netscape-5-" + strconv.Itoa(pid) + ":" + strconv.Itoa(count) + "@user&heartbeat=60"
		ws, err := websocket.Dial(url, "", origin)
		checkErr(err)

		msg := make([]byte, 512)
		_, err = ws.Read(msg)
		checkErr(err)

		data := []byte("h")
		ticker := time.NewTicker(5 * time.Second)
		i := 0
		for _ = range ticker.C {
			websocket.Message.Send(ws, string(data))
			_, err := ws.Read(msg)
			checkErr(err)
			if i > count {
				ws.Close()

				break
			}

			i++
		}
	}

}
コード例 #16
0
ファイル: tls.go プロジェクト: russ168/golem
func DialWebSocket(url string) (*websocket.Conn, error) {
	origin, err := os.Hostname()
	if err != nil {
		logger.Warn(err)
	}
	return websocket.Dial(url, "", fmt.Sprintf("http://%v", origin))
}
コード例 #17
0
ファイル: prime_wsc.go プロジェクト: vachu/prime
func main() {
	flag.Parse()
	fmt.Fprintln(os.Stderr, "INFO: Connecting to WebSocket Server @", *wsUrl, "...")
	ws, err := websocket.Dial(*wsUrl, "", "http://localhost")
	if err != nil {
		fmt.Fprintf(os.Stderr, "ERROR: connecting to %s - %s\n", wsUrl, err)
		return
	}
	fmt.Fprintln(os.Stderr, "INFO: Connected\n")

	for msg := "?"; msg != "EXIT" && msg != "QUIT" && msg != "CLOSE"; msg = getLine() {
		err = websocket.Message.Send(ws, msg)
		if err != nil {
			fmt.Fprintln(os.Stderr, "ERROR: could not send Websocket request - ", err)
			continue
		}

		err = websocket.Message.Receive(ws, &msg)
		msg = strings.Trim(msg, " \t\v\f\r\n")
		for err == nil && msg != "==== EOT ====" {
			fmt.Println(msg)

			err = websocket.Message.Receive(ws, &msg)
			msg = strings.Trim(msg, " \t\v\f\r\n")
		}
		fmt.Print("Enter Request / Command: ")
	}
	websocket.Message.Send(ws, "CLOSE")
	ws.Close()
}
コード例 #18
0
ファイル: dispatcher_test.go プロジェクト: james4k/wsevents
func TestClientSideClose(t *testing.T) {
	var simpleHandler *SimpleHandler
	closeChan := make(chan bool)
	onNew := func(handler wsevents.EventHandler) {
		var ok bool
		simpleHandler, ok = handler.(*SimpleHandler)
		if !ok {
			t.Fatal("handler was not a *SimpleHandler")
		}

		simpleHandler.CloseChan = closeChan
	}

	serv := httptest.NewServer(wsevents.Handler(&SimpleHandler{}, onNew))

	origin := serv.URL
	url := "ws" + serv.URL[4:]
	_, err := websocket.Dial(url, "", origin)
	if err != nil {
		t.Error(err)
	}

	serv.CloseClientConnections()

	select {
	case <-closeChan:
		if simpleHandler.Connection == nil {
			t.Fatal("OnOpen was not called!")
		}
	case <-time.After(1 * time.Second):
		t.Fatal("did not get notified of close!")
	}
}
コード例 #19
0
func TestWorkerFlow(t *testing.T) {
	w, err := NewWorker(fmt.Sprintf("wr://%[email protected]:8091/test", v.AccessToken()))
	if err != nil {
		t.Fatalf("Expected to connect the worker, error: %v", err)
	}
	go func() {
		ws, _ := websocket.Dial("ws://127.0.0.1:8090/test", "ws", "http://127.0.0.1/")
		token := v.GenerateSingleAccessToken("joe", ".*")
		var resp map[string]interface{}
		websocket.JSON.Receive(ws, &resp)
		websocket.JSON.Send(ws, map[string]interface{}{
			"auth": map[string]interface{}{
				"token": token,
			},
		})
		websocket.JSON.Receive(ws, &resp)
		websocket.JSON.Send(ws, map[string]interface{}{
			"trigger": map[string]interface{}{
				"event": "test",
				"data":  map[string]interface{}{"foo": "bar"},
			},
		})
	}()
	msg := <-w.Run()
	if msg.Event != "test" || msg.Data["foo"] != "bar" {
		t.Errorf("Expected to get the test event, got: %v", msg.Event)
	}
	w.Stop()
}
コード例 #20
0
ファイル: ws_client.go プロジェクト: nicnys-8/mdc
func (wsClient *wsClientType) connect(ipAddress string) {
	origin := "http://localhost/"
	url := "ws://" + ipAddress + "/node"

	var err error
	wsClient.ws, err = websocket.Dial(url, "", origin)
	if err != nil {
		info("failed to connect to supernode at " + ipAddress + ", connection refused")
		os.Exit(0)
	}

	remoteNode := wsClient.handshake()

	wsClient.remoteNodeChannel <- remoteNode

	for {
		msg := wsClient.receive()

		if msg == nil {
			// TODO: remove the link
			return
		}
		wsClient.msgChannel <- *msg
	}
}
コード例 #21
0
ファイル: transporter_test.go プロジェクト: hycxa/kylin
func TestTransporter(t *testing.T) {
	gob.Register(testMessage{})
	http.Handle("/echo", websocket.Handler(testTransporterEchoServer))
	go func() {
		err := http.ListenAndServe(":20001", nil)
		if err != nil {
			t.Fatal(err.Error())
		}
	}()

	ws, err := websocket.Dial("ws://localhost:20001/echo", "", "ws://localhost/client")
	if err != nil {
		t.Fatal(err.Error())
	}

	var transporter Transporter
	var result string

	onMessage := DispatcherFunc(func(message interface{}) error {
		result = message.(testMessage).Info
		transporter.Stop()
		return nil
	})
	onError := ErrorHandlerFunc(func(err error) {
		log.Println(err)
	})
	transporter = NewTransporter(getEncoder(ws), getDecoder(ws), onMessage, onError)
	transporter.Start()
	transporter.Send(&testMessage{"Hello"})
	transporter.WaitForDone()
	if result != "Hello" {
		t.Fail()
	}
}
コード例 #22
0
ファイル: cli.go プロジェクト: zond/virtus
func main() {
	flag.Parse()
	if flag.NArg() == 1 {
		origin := "http://localhost/"
		url := flag.Arg(0)
		ws, err := websocket.Dial(url, "", origin)
		if err != nil {
			panic(fmt.Sprint("While trying to connect to ", url, ": ", err))
		}
		in := make(chan string)
		out := make(chan interface{})
		go receive(ws, in)
		go read(out)
		for {
			select {
			case s, ok := <-in:
				if ok {
					fmt.Println(s)
				} else {
					return
				}
			case d := <-out:
				websocket.JSON.Send(ws, d)
			}
		}
	} else {
		fmt.Fprintln(os.Stderr, "Usage: cli URL")
	}
}
コード例 #23
0
ファイル: client.go プロジェクト: keshavdv/subway
func Main() {
	kingpin.Parse()

	// Create websocket session for tunnels
	origin := fmt.Sprintf("http://%s/", *host)
	url := fmt.Sprintf("ws://%s/", *host)
	conn, err := websocket.Dial(url, "", origin)
	if err != nil {
		log.Fatal(fmt.Sprintf("Could not connect to subway server (%s)!", url))
	}

	session, err := yamux.Client(conn, nil)
	if err != nil {
		panic(err)
	}

	// Start REST api
	router := mux.NewRouter()
	router.HandleFunc("/", handlers.CreateTunnel)

	n := negroni.New()
	n.Use(negronilogrus.NewMiddleware())
	render := render.New(render.Options{})
	subway := context.CreateSubway(session, render)
	n.Use(subway)
	n.UseHandler(router)
	n.Run(fmt.Sprintf(":%v", *port))

}
コード例 #24
0
ファイル: server_test.go プロジェクト: GlenKelley/battleref
func TestReplayStream(test *testing.T) {
	ServerTest(test, func(t *testutil.T, server *ServerState) {
		go server.Serve()
		//Race condition of server not starting
		time.Sleep(time.Microsecond)
		defer sendPost(t, server, "/shutdown", nil)
		sendJSONPost(t, server, "/register", map[string]string{"name": "NameFoo", "public_key": SamplePublicKey, "category": string(tournament.CategoryBattlecode2016)})
		sendJSONPost(t, server, "/map/create", map[string]string{"name": "NameBar", "source": "SourceBar", "category": string(tournament.CategoryBattlecode2016)})
		r := sendGet(t, server, "/commits?name=NameFoo&category="+string(tournament.CategoryBattlecode2016))
		commit := Json(t, r).Key("data").Key("commits").At(0).String()
		r = sendJSONPost(t, server, "/match/run", map[string]string{"player1": "NameFoo", "player2": "NameFoo", "category": string(tournament.CategoryBattlecode2016), "commit1": commit, "commit2": commit, "map": "NameBar"})
		id := Json(t, r).Key("data").Key("id").Int()
		msg := make([]byte, 4096)
		if ws, err := websocket.Dial(fmt.Sprintf("ws://localhost:8081/replay/stream?id=%v", id), "", "http://localhost"); err != nil {
			t.ErrorNow(err)
		} else {
			var err error
			for err == nil {
				if _, err = ws.Write([]byte("")); err != nil {
					t.ErrorNow(err)
				} else if _, err = ws.Read(msg); err != io.EOF && err != nil {
					t.ErrorNow(err)
				}
			}
		}
	})
}
コード例 #25
0
ファイル: wsbench.go プロジェクト: checkraiser-clj/http-kit
func bench(concurrency chan int, total chan int) {
	count := rand.Intn(10000) + 1000
	ws, err := websocket.Dial(wsurl, "", origin)
	if err != nil {
		log.Fatal(err)
		return
	}

	for i := 0; i < count; i++ {
		c := *messageSize
		bytes := make([]byte, c)
		for j := 0; j < c; j++ {
			bytes[j] = 65
		}
		if _, err := ws.Write(bytes); err != nil {
			log.Fatal(err)
		}

		msg := make([]byte, 1024)
		if n, err := ws.Read(msg); err != nil {
			log.Fatal(err)
		} else if n != c {
			log.Printf("expected length %d, actual %d", c, n)
		}
	}
	total <- count                                                 // let other gorutine compute total
	log.Printf("#%d finished %d requests\n", <-concurrency, count) //  allow others to run
}
コード例 #26
0
ファイル: PersonClientJSON.go プロジェクト: jchjjj/learnGo
func main() {
	if len(os.Args) != 2 {
		fmt.Println("Usage: ", os.Args[0], "ws://*****:*****@newmarch.name", "*****@*****.**"},
	}
	for {
		err = websocket.JSON.Send(conn, person)
		if err != nil {
			fmt.Println("Couldn't send msg " + err.Error())
		}
		err = websocket.Message.Receive(conn, &msg)
		checkError(err)
		fmt.Println("recv from server: ", msg)
	}

	os.Exit(0)
}
コード例 #27
0
ファイル: client.go プロジェクト: kirs/live-console
func main() {
	ws, err := websocket.Dial("ws://localhost:1235/", "", "http://localhost:1235/")
	if err != nil {
		panic(err)
	}

	var resp = make([]byte, 4096)
	for {
		n, err := ws.Read(resp)
		if err != nil {
			panic(err)
		}

		var now, received string
		received = string(resp[0:n])

		now = time.Now().Format(time.RFC822)
		now += " "

		terminal.Stdout.Color("y").
			Print(now).Reset().Color("g").
			Print(received).Nl()

		sendToNc(received)
	}
}
コード例 #28
0
ファイル: runtime_test.go プロジェクト: h2park/goflow
// 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")
	}
}
コード例 #29
0
ファイル: main.go プロジェクト: samofly/gentle
func main() {
	flag.Parse()

	if *url == "" {
		log.Fatal("-url not specified")
	}

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

	go read(ws)

	s := bufio.NewScanner(os.Stdin)
	for s.Scan() {
		if _, err := ws.Write([]byte(fmt.Sprintf("%s\n", s.Text()))); err != nil {
			log.Fatal(err)
		}
	}
	if err := s.Err(); err != nil {
		log.Fatal(err)
	}
}
コード例 #30
0
// Connect create new bitfinex websocket connection
func (w *WebSocketService) Connect() error {
	ws, err := websocket.Dial(WebSocketURL, "", "http://localhost/")
	if err != nil {
		return err
	}
	w.ws = ws
	return nil
}