當前位置: 首頁>>代碼示例>>Golang>>正文


Golang websocket.Dial函數代碼示例

本文整理匯總了Golang中code/google/com/p/go/net/websocket.Dial函數的典型用法代碼示例。如果您正苦於以下問題:Golang Dial函數的具體用法?Golang Dial怎麽用?Golang Dial使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Dial函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: doConnect

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
	}
}
開發者ID:papmech,項目名稱:Distributed-2048,代碼行數:56,代碼來源:cmdlineclient_impl.go

示例2: main

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)
}
開發者ID:nandopeters,項目名稱:goplay,代碼行數:35,代碼來源:rootH.go

示例3: main

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)
}
開發者ID:foamdino,項目名稱:learning-go,代碼行數:31,代碼來源:wsclient.go

示例4: poundSock

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
}
開發者ID:jrconlin,項目名稱:go_pound,代碼行數:60,代碼來源:pound.go

示例5: handleConnection

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
}
開發者ID:eduardostalinho,項目名稱:flashproxy,代碼行數:34,代碼來源:websocket-client.go

示例6: TestThatItSends

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))
}
開發者ID:shageman,項目名稱:loggregator,代碼行數:30,代碼來源:cf_sink_test.go

示例7: main

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)
	}
}
開發者ID:bonly,項目名稱:exercise,代碼行數:34,代碼來源:20120112_websocket_chat_cli.go

示例8: TestWebsocketHandlerJSON

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)
	}
}
開發者ID:borh,項目名稱:natsume-cabocha-bindings,代碼行數:25,代碼來源:example-server_test.go

示例9: testNotificationWithWebsocket

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("[email protected]", 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)
	}
}
開發者ID:Pronovix,項目名稱:gopush,代碼行數:26,代碼來源:gopush_test.go

示例10: Dial

// 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
}
開發者ID:univedo,項目名稱:univedo-go,代碼行數:33,代碼來源:connection.go

示例11: Connect

// 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
}
開發者ID:tenntenn,項目名稱:netchan,代碼行數:35,代碼來源:client.go

示例12: TestStreamService

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)
		}
	}

}
開發者ID:yanatan16,項目名稱:gochat,代碼行數:60,代碼來源:stream_service_test.go

示例13: CreateWsConn

// 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
}
開發者ID:yml,項目名稱:wsbench,代碼行數:8,代碼來源:wsbench.go

示例14: checkNames

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
	}

}
開發者ID:kazuroka,項目名稱:chat,代碼行數:32,代碼來源:main.go

示例15: NewRemoveConn

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++
		}
	}

}
開發者ID:ming-hai,項目名稱:appmsgsrv,代碼行數:31,代碼來源:websocket.go


注:本文中的code/google/com/p/go/net/websocket.Dial函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。