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


Golang websocket.Conn類代碼示例

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


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

示例1: clientHandler

func clientHandler(ws *websocket.Conn) {
	defer func() {
		subscriptionChan <- subscription{ws, false}
		ws.Close()
	}()

	subscriptionChan <- subscription{ws, true}

	for {
		buf := make([]byte, 128)
		n, err := ws.Read(buf)
		if err != nil {
			log.Print("Reading Buffer: ", err)
			break
		}

		var m message
		err = json.Unmarshal(buf[0:n], &m)
		if err != nil {
			log.Print("Parsing JSON: ", buf, m, err)
			break
		}

		messageChan <- message{m.Text, m.Id, m.User, m.Command}
	}
}
開發者ID:matt-west,項目名稱:gochat,代碼行數:26,代碼來源:chat.go

示例2: handleWebSocket

func handleWebSocket(conn *websocket.Conn) {
	respStatus := http.StatusOK
	defer func() {
		conn.Close()
		logRequest(HTTPS_WEBSOCKET, respStatus, conn.Request().Host, conn.Request())
	}()
	request := make([]byte, 1024)
	for {
		n, err := conn.Read(request)
		if err != nil {
			if debugMode {
				log.Error("Error reading on WebSocket: %s", err)
			}
			break
		}
		response, status := getLiveItems(string(request[:n]))
		if status != http.StatusOK {
			respStatus = status
			break
		}
		if len(response) != 0 {
			if _, err = conn.Write(response); err != nil {
				break
			}
		}
	}
}
開發者ID:elimisteve,項目名稱:togethr,代碼行數:27,代碼來源:live-server.go

示例3: clientHandler

/*
 * Get messages from client
 */
func clientHandler(ws *websocket.Conn) {
	defer func() {
		log.Println("Client handler closed.")
		ws.Close()
	}()

	buf := make([]byte, 256)
	stopCh := make(chan bool)
	var input ProcessInput
	for {
		n, err := ws.Read(buf)
		if err != nil {
			break
		}

		// get data
		err = json.Unmarshal(buf[0:n], &input)
		if err != nil {
			stopCh <- true
			break
		}

		workChan <- Work{ws, &input, stopCh}
	}
}
開發者ID:egonelbre,項目名稱:sivq,代碼行數:28,代碼來源:server.go

示例4: LobbyServer

func LobbyServer(ws *websocket.Conn) {
	reader := bufio.NewReader(ws)
	var username string
	var player *Player
	connected := false
	sendPlayers(ws)
	inGame := false

	for {
		br, er := reader.ReadString('\n')
		if er == os.EOF {
			break
		}

		msg := strings.Split(br, " ")

		switch msg[0] {
		case "connect":
			username = strings.TrimSpace(msg[1])

			if _, ok := users[username]; !ok && !connected {
				player = &Player{Name: username, Socket: ws}
				sendPlayer(player)
				users[username] = player
				fmt.Printf("Got connection from %s\n", username)
				connected = true
			} else {
				fmt.Fprint(ws, "error Username Exists")
				ws.Close()
				return
			}
		case "create":
			if inGame {
				fmt.Fprint(ws, "error Already in a game")
				continue
			}
			fmt.Printf("Create %s\n", username)
			sendPlayer(player)
			inGame = true
			continue

		case "start":
			fmt.Printf("Game %s\n", br)
			for _, info := range users {
				fmt.Fprintf(info.Socket, "Game %s", "start")
			}

		case "point":
			user := strings.TrimSpace(msg[1])
			point, _ := strconv.Atoi(strings.TrimSpace(msg[2]))
			player = &Player{Name: user, Point: point, Socket: ws}
			sendPlayer(player)
			users[username] = player
			continue

		default:
			fmt.Printf("Unknown message: %s\n", br)
		}
	}
}
開發者ID:uglybrd,項目名稱:GoGameHTML5,代碼行數:60,代碼來源:server.go

示例5: HandleWebsocket

// handle receives messages on the given websocket connection, decoding them
// from JSON to a Msg object. It adds a channel to listeners, encoding messages
// received on the listener channel as JSON, then sending it over the connection.
func (r *Router) HandleWebsocket(c *websocket.Conn) {
	u, err := url.Parse(c.LocalAddr().String())
	if err != nil {
		log.Println(err)
		return
	}

	// split url path into components, e.g.
	// url: http://leeps.ucsc.edu/redwood/session/1/[email protected]
	// path: /redwood/session/1/[email protected]
	// -> [redwood, session, 1, [email protected]]
	components := strings.Split(u.Path, "/")

	// map components into instance_prefix, session_id, and subject_name
	var instance, session_id_string, subject_name string
	if len(components) >= 4 {
		instance = components[1]
		session_id_string = components[2]
		subject_name = components[3]
	} else {
		session_id_string = components[1]
		subject_name = components[2]
	}

	session_id, err := strconv.Atoi(session_id_string)
	if err != nil {
		log.Println(err)
		return
	}

	var subject *Subject
	if subject_name == "admin" || subject_name == "listener" {
		subject = &Subject{name: subject_name, period: -1, group: -1}
	} else {
		// put in a request to the server loop for the given subject object
		// this ensures only one subject object exists per session/name pair
		request := &SubjectRequest{instance: instance, session: session_id, name: subject_name, response: make(chan *Subject)}
		r.requestSubject <- request
		subject = <-request.response
	}
	if subject == nil {
		log.Panicln("nil subject")
	}

	listener := NewListener(r, instance, session_id, subject, c)
	ack := make(chan bool)
	r.newListeners <- &ListenerRequest{listener, ack}
	// wait for listener to be registered before starting sync
	<-ack

	log.Printf("STARTED SYNC: %s\n", subject.name)
	listener.Sync()
	log.Printf("FINISHED SYNC: %s\n", subject.name)

	go listener.SendLoop()
	listener.ReceiveLoop()
}
開發者ID:RedwoodAdmin,項目名稱:RedwoodFramework,代碼行數:60,代碼來源:router.go

示例6: IsClosed

func IsClosed(ws *websocket.Conn) bool {
	var ibuff [50]byte

	_, err := ws.Read(ibuff[0:50])
	if err != nil {
		return true
	}

	return false
}
開發者ID:hpcorona,項目名稱:webtalk,代碼行數:10,代碼來源:main.go

示例7: ReadThread

func ReadThread(ws *websocket.Conn, msg []byte, ch chan int) {
	for {
		n, error := ws.Read(msg)
		if error != nil {
			fmt.Println("WebSocket read error: ", error)
			ch <- 0
			break
		}
		ch <- n
		if n == 0 {
			break
		}
	}
}
開發者ID:Saikees,項目名稱:practice,代碼行數:14,代碼來源:websocket.go

示例8: throwFatal

func throwFatal(ws *websocket.Conn, reason string) {
	msg := message{
		Channel: "",
		Data: map[string]string{
			"response": "error",
			"reason":   reason,
		},
		Auth: Auth{},
		Mode: "error",
	}
	websocket.JSON.Send(ws, msg)
	unsubscribe(ws)
	ws.Close()
}
開發者ID:klinster,項目名稱:Bessie,代碼行數:14,代碼來源:websockets.go

示例9: Handle

func Handle(ws *websocket.Conn) {
	fmt.Println("New Connection.")
	encoder := json.NewEncoder(ws)
	i := 0
	for _, line := range lines {
		i++
		if i > 47 {
			time.Sleep(time.Duration((rand.Intn(2000) + 700) * int(time.Millisecond)))
		}
		data := struct{ Server, Line string }{"irc.foonetic.net", line}
		encoder.Encode(data)
	}
	fmt.Println("Conn closed.")
	ws.Close()
}
開發者ID:CasualSuperman,項目名稱:GoIRC,代碼行數:15,代碼來源:goirc.go

示例10: sub

func sub(ws *websocket.Conn) {
	println("Beginning Sub")

	var resp = make([]byte, 512)
	for {
		println("Waiting Read")
		_, err := ws.Read(resp)

		if err != nil {
			panic(err)
		}
		// fmt.Println("Received 1:", string(resp[0:n]))
		// fmt.Println("Received %v:", n)
		ch <- 1
	}
}
開發者ID:blindsey,項目名稱:wsbench,代碼行數:16,代碼來源:broadcast_client.go

示例11: handler

func handler(ws *websocket.Conn) {
	x := 0.
	for {
		if x >= 2*math.Pi {
			x = 0
		} else {
			x += 0.05
		}

		time.Sleep(500 * 1000 * 1000) // sleep for 500ms (Sleep takes nanoseconds)

		msg := strconv.Ftoa64(math.Sin(x), 'g', 10)
		log.Printf("%v sending: %v\n", ws, msg)
		ws.Write([]byte(msg))
	}
}
開發者ID:svenlange,項目名稱:websocket,代碼行數:16,代碼來源:server.go

示例12: doWebSocket

/*
websocket接收發送消息
*/
func doWebSocket(w http.ResponseWriter, r *http.Request, conn *websocket.Conn) {
	for {
		var inputData []byte
		msgType, inputData, err := conn.ReadMessage()
		if err != nil {
			logger.Println(tag_customRoute, err)
			return
		}
		logger.Println(tag_customRoute, "receive data:"+string(inputData))
		err = conn.WriteMessage(msgType, inputData)
		if err != nil {
			logger.Println(tag_customRoute, err)
			return
		}
	}
}
開發者ID:zhangxx110,項目名稱:SimpleForumByGo,代碼行數:19,代碼來源:customRoute.go

示例13: clientHandler

func clientHandler(ws *websocket.Conn) {
	defer func() {
		subscriptionChan <- subscription{ws, false}
		ws.Close()
	}()

	subscriptionChan <- subscription{ws, true}

	buf := make([]byte, 256)
	for {
		n, err := ws.Read(buf)
		if err != nil {
			break
		}
		messageChan <- buf[0:n]
	}
}
開發者ID:ngd,項目名稱:chrome-bench,代碼行數:17,代碼來源:flicker.go

示例14: send

func send(ws *websocket.Conn, path string, evs <-chan store.Event) {
	l := len(path) - 1
	for ev := range evs {
		ev.Getter = nil // don't marshal the entire snapshot
		ev.Path = ev.Path[l:]
		b, err := json.Marshal(ev)
		if err != nil {
			log.Println(err)
			return
		}
		_, err = ws.Write(b)
		if err != nil {
			log.Println(err)
			return
		}
	}
}
開發者ID:Br3nda,項目名稱:doozerd,代碼行數:17,代碼來源:web.go

示例15: socketHandler

func socketHandler(c *websocket.Conn) {
	in, out := make(chan *Message), make(chan *Message)
	errc := make(chan error, 1)

	// Decode messages from client and send to the in channel.
	go func() {
		dec := json.NewDecoder(c)
		for {
			var m Message
			if err := dec.Decode(&m); err != nil {
				errc <- err
				return
			}
			in <- &m
		}
	}()

	// Receive messages from the out channel and encode to the client.
	go func() {
		enc := json.NewEncoder(c)
		for m := range out {
			if err := enc.Encode(m); err != nil {
				errc <- err
				return
			}
		}
	}()

	// open a connection to minimega and handle the request
	megaconns := make(map[string]*megaconn)
	for {
		select {
		case m := <-in:
			log.Debugln("running snippet from:", c.Request().RemoteAddr)
			lOut := limiter(in, out)
			megaconns[m.Id] = runMega(m.Id, m.Body, lOut)
		case err := <-errc:
			if err != io.EOF {
				// A encode or decode has failed; bail.
				log.Errorln(err)
			}
			return
		}
	}
}
開發者ID:npe9,項目名稱:minimega,代碼行數:45,代碼來源:socket.go


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