当前位置: 首页>>代码示例>>Golang>>正文


Golang Conn.Request方法代码示例

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


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

示例1: WebsocketHandler

func WebsocketHandler(ws *websocket.Conn) {
	key := ws.Request().Header.Get("Sec-Websocket-Key")

	client := Client{ws, key}
	Srv.register(client)

	defer func() {
		Srv.unregister(client)
	}()

	for {
		msg := make([]byte, 512)
		n, err := ws.Read(msg)

		if err != nil {
			break
		}

		var cmd Command
		json.Unmarshal(msg[:n], &cmd)

		log.Println(cmd.Event)

		client.process(cmd)
	}
}
开发者ID:dfernandez,项目名称:colernio-backend,代码行数:26,代码来源:websocket.go

示例2: SockServer

func SockServer(ws *websocket.Conn) {
	var err error
	var clientMessage string
	// use []byte if websocket binary type is blob or arraybuffer
	// var clientMessage []byte
	defer func() {
		if err = ws.Close(); err != nil {
			log.Println("Websocket could not be closed", err.Error())
		}
	}()

	client := ws.Request().RemoteAddr
	log.Println("Client connected:", client)
	sockCli := ClientConn{ws, client}
	ActiveClients[sockCli] = 0
	log.Println("Number of clients connected ...", len(ActiveClients))

	for {
		if err = Message.Receive(ws, &clientMessage); err != nil {
			log.Println("Websocket Disconnected waiting", err.Error())
			delete(ActiveClients, sockCli)
			log.Println("Number of clients still connected ...", len(ActiveClients))
			return
		}

		if len(clientMessage) > 0 {
			clientMessage = sockCli.clientIP + " Said: " + clientMessage
			for cs, _ := range ActiveClients {
				if err = Message.Send(cs.websocket, clientMessage); err != nil {
					log.Println("Could not send message to ", cs.clientIP, err.Error())
				}
			}
		}
	}
}
开发者ID:Chubik,项目名称:chat,代码行数:35,代码来源:chat.go

示例3: BuildConnection

func BuildConnection(ws *websocket.Conn) {
	email := ws.Request().URL.Query().Get("email")

	if email == "" {
		return
	}

	onlineUser := &OnlineUser{
		InRoom:     runningActiveRoom,
		Connection: ws,
		Send:       make(chan Message, 256),
		UserInfo: &User{
			Email:    email,
			Name:     strings.Split(email, "@")[0],
			Gravatar: libs.UrlSize(email, 20),
		},
	}
	runningActiveRoom.OnlineUsers[email] = onlineUser

	m := Message{
		MType: STATUS_MTYPE,
		UserStatus: UserStatus{
			Users: runningActiveRoom.GetOnlineUsers(),
		},
	}
	runningActiveRoom.Broadcast <- m

	go onlineUser.PushToClient()
	onlineUser.PullFromClient()

	onlineUser.killUserResource()
}
开发者ID:piclez,项目名称:gochatting,代码行数:32,代码来源:chat_ws.go

示例4: websocketUploadServer

func websocketUploadServer(ws *websocket.Conn) {
	dlId := ws.Request().URL.Path[len("/api/upload_ws/"):]
	bf := GetBounceFile(dlId)
	if bf == nil {
		ws.Write([]byte("ERROR! Download with this ID does not exist."))
		return
	}

	var dataBuffer [50000]byte // 50 KB arbitrary
	total := 0
	for {
		numBytes, err := ws.Read(dataBuffer[:])
		total += numBytes
		dataCopy := append([]byte{}, dataBuffer[:numBytes]...)

		bf.SendData(dataCopy)
		if err == io.EOF {
			break
		}

		if err != nil { // Oops!
			ws.Write([]byte("ERROR! " + err.Error()))
			break
		}
		ws.Write([]byte("OK"))
	}
}
开发者ID:fsufitch,项目名称:fwooshfile,代码行数:27,代码来源:upload_websocket.go

示例5: handleWss

func handleWss(wsconn *websocket.Conn) {
	p := Responder{nil, wsconn.Request(), time.Now()}
	serverIP := wsconn.Request().Header.Get("X-Server-IP")

	conn, err := net.Dial("tcp", serverIP)
	if err != nil {
		p.errorLog(http.StatusInternalServerError, "Error connecting to '%s': %s", serverIP, err.Error())
		wsconn.Close()
		return
	}
	defer conn.Close()
	defer wsconn.Close()

	wsconn.PayloadType = websocket.BinaryFrame

	t := &copySyncer{alive: true}

	go p.CopyR2W(t, conn, wsconn, serverIP+" ws2vnc")
	go p.CopyR2W(t, wsconn, conn, serverIP+" vnc2ws")

	p.errorLog(http.StatusOK, "websocket started: '%s'", serverIP)

	for t.IsAlive() {
		time.Sleep(100 * time.Millisecond)
	}

	p.errorLog(http.StatusOK, "websocket closed: '%s'", serverIP)
}
开发者ID:gitinsky,项目名称:vnc-go-web,代码行数:28,代码来源:webSocket.go

示例6: ServeWebSocket

func ServeWebSocket(ws *websocket.Conn) {
	segs := strings.Split(ws.Request().URL.Path, "/")
	if len(segs) < 2 {
		log.Println("No token in incoming request, dropped")
		websocket.JSON.Send(ws, "No token in incoming request, dropped")
		return
	}

	ak, err := LoadKey(segs[1])
	if err != nil {
		log.Println(err.Error())
		websocket.JSON.Send(ws, err.Error())
		return
	}

	if ak.UsageIsLimited() {
		err = ak.ConsumeUsage()
		if err != nil {
			log.Println(err.Error())
			websocket.JSON.Send(ws, err.Error())
			return
		}
	}

	socket := NewSocket(ak, ws)
	go socket.ListenToRedis()
	go socket.ListenToSocket()

	socket.Wait()
}
开发者ID:pote,项目名称:philote,代码行数:30,代码来源:main.go

示例7: handler

func (l *listener) handler(ws *websocket.Conn) {
	l.lock.Lock()

	if !l.running {
		ws.Close()
		l.lock.Unlock()
		return
	}

	w := &wsPipe{ws: ws, addr: l.addr, proto: l.proto, open: true}
	w.iswss = l.iswss

	req := ws.Request()

	w.props = make(map[string]interface{})
	w.props[mangos.PropLocalAddr] = ws.LocalAddr()
	w.props[mangos.PropRemoteAddr], _ = net.ResolveTCPAddr("tcp", req.RemoteAddr)

	if l.iswss {
		w.props[mangos.PropTlsConnState] = *req.TLS
	}

	w.wg.Add(1)
	l.pending = append(l.pending, w)
	l.cv.Broadcast()
	l.lock.Unlock()

	// We must not return before the socket is closed, because
	// our caller will close the websocket on our return.
	w.wg.Wait()
}
开发者ID:rlhatcher,项目名称:mangos,代码行数:31,代码来源:ws.go

示例8: wslogsHandler

func (ws *WebSocketServer) wslogsHandler(w *websocket.Conn) {
	source := w.Request().FormValue("source")
	host := fmt.Sprintf("%s/%d", w.RemoteAddr().String(), time.Now().UnixNano())

	defer func() {
		log.Printf("[%s - %s] closing websocket conn", ws.name, w.RemoteAddr().String())
		ws.b.DelSubscriber(host)
		w.Close()
	}()

	log.Printf("[%s - %s] accepting websocket conn", ws.name, w.RemoteAddr().String())

	r := make(chan *buffer.Event, recvBuffer)
	ws.b.AddSubscriber(host, r)

	for {
		select {
		case ev := <-r:
			if len(source) > 0 {
				if ev.Source != source {
					continue
				}
			}

			err := websocket.Message.Send(w, *ev.Text)
			if err != nil {
				log.Printf("[%s] error sending ws message: %v", w.RemoteAddr().String(), err.Error())
				return
			}
		}
	}
}
开发者ID:packetzoom,项目名称:logzoom,代码行数:32,代码来源:websocket.go

示例9: BuildConnection

func BuildConnection(ws *websocket.Conn) {
	log.Info("BuildConnection()")
	token := ws.Request().URL.Query().Get("token")
	log.Debug(token)
	var uci userConnectionInfo
	err := validateToken(token, time.Now(), ws.RemoteAddr(), &uci)
	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
		}).Error("validation error")
		// how should this reply to the client?
		return
	}

	onlineUser := &OnlineUser{
		Connection: ws,
		Uci:        uci,
		Send:       make(chan envelope, 256),
	}
	runningRoom.Users[onlineUser] = true
	go onlineUser.PushToClient()
	onlineUser.PullFromClient()
	delete(runningRoom.Users, onlineUser)
	log.Info("tore down user connection")
}
开发者ID:thraxil,项目名称:windsock,代码行数:25,代码来源:windsock.go

示例10: addLogs

func addLogs(ws *websocket.Conn) {
	var err error
	defer func() {
		data := map[string]interface{}{}
		if err != nil {
			data["error"] = err.Error()
			log.Error(err.Error())
		} else {
			data["error"] = nil
		}
		msg, _ := json.Marshal(data)
		ws.Write(msg)
		ws.Close()
	}()
	req := ws.Request()
	t := context.GetAuthToken(req)
	if t == nil {
		err = fmt.Errorf("wslogs: no token")
		return
	}
	if t.GetAppName() != app.InternalAppName {
		err = fmt.Errorf("wslogs: invalid token app name: %q", t.GetAppName())
		return
	}
	err = scanLogs(ws)
	if err != nil {
		return
	}
}
开发者ID:pedrosnk,项目名称:tsuru,代码行数:29,代码来源:log.go

示例11: AppLogs

func AppLogs(ws *websocket.Conn) *httperr.Error {
	app := mux.Vars(ws.Request())["app"]
	header := ws.Request().Header

	var err error

	follow := true
	if header.Get("Follow") == "false" {
		follow = false
	}

	since := 2 * time.Minute
	if s := header.Get("Since"); s != "" {
		since, err = time.ParseDuration(s)
		if err != nil {
			return httperr.Errorf(403, "Invalid duration %s", s)
		}
	}

	err = models.Provider().LogStream(app, ws, structs.LogStreamOptions{
		Filter: header.Get("Filter"),
		Follow: follow,
		Since:  time.Now().Add(-1 * since),
	})
	if err != nil {
		if strings.HasSuffix(err.Error(), "write: broken pipe") {
			return nil
		}
		return httperr.Server(err)
	}
	return nil
}
开发者ID:gmelika,项目名称:rack,代码行数:32,代码来源:apps.go

示例12: AppLogs

func AppLogs(ws *websocket.Conn) error {
	defer ws.Close()

	app := mux.Vars(ws.Request())["app"]

	a, err := models.GetApp(app)

	if awsError(err) == "ValidationError" {
		return fmt.Errorf("no such app: %s", app)
	}

	if err != nil {
		return err
	}

	logs := make(chan []byte)
	done := make(chan bool)

	a.SubscribeLogs(logs, done)

	for data := range logs {
		ws.Write(data)
	}

	return nil
}
开发者ID:jbuck,项目名称:rack,代码行数:26,代码来源:apps.go

示例13: addLogs

func addLogs(ws *websocket.Conn) {
	var err error
	defer func() {
		msg := &errMsg{}
		if err != nil {
			msg.Error = err.Error()
			log.Errorf("failure in logs webservice: %s", err)
		}
		websocket.JSON.Send(ws, msg)
		ws.Close()
	}()
	req := ws.Request()
	t := context.GetAuthToken(req)
	if t == nil {
		err = errors.Errorf("wslogs: no token")
		return
	}
	if t.GetAppName() != app.InternalAppName {
		err = errors.Errorf("wslogs: invalid token app name: %q", t.GetAppName())
		return
	}
	err = scanLogs(ws)
	if err != nil {
		return
	}
}
开发者ID:tsuru,项目名称:tsuru,代码行数:26,代码来源:log.go

示例14: ircHandler

func ircHandler(ws *websocket.Conn) {
	var err error
	var clientmessage string

	current := ClientConn{ws, ws.Request().RemoteAddr}
	clients[current] = 0

	fmt.Println("number of clients connected ", len(clients))

	for {
		if err = message.Receive(ws, &clientmessage); err != nil {
			delete(clients, current)
			fmt.Println("client disconnect,", len(clients), " clients remain")
			return
		}

		clientmessage = "<" + hash(current.ip) + "> " + clientmessage

		for cs, _ := range clients {
			if err = message.Send(cs.websocket, clientmessage); err != nil {
				fmt.Println("sending failed")
			}
		}
	}
}
开发者ID:iotek,项目名称:unix.chat,代码行数:25,代码来源:irc.go

示例15: onConnectionOpened

/**
 * Event -> On connection opened
 */
func (server *server) onConnectionOpened(conn *websocket.Conn) {
	defer server.Close(conn)

	log.Printf("Connection opened: %v", conn.Request().RemoteAddr)
	client := NewClient(conn, server)
	server.startClient(client)
}
开发者ID:stevejmason,项目名称:go-websockets,代码行数:10,代码来源:server.go


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