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


Golang Server.Handshake方法代碼示例

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


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

示例1: AddListener

func (h *Hrotti) AddListener(name string, config *ListenerConfig) error {
	listener := &internalListener{name: name, url: *config.URL}
	listener.stop = make(chan struct{})

	h.listeners[name] = listener

	ln, err := net.Listen("tcp", listener.url.Host)
	if err != nil {
		ERROR.Println(err.Error())
		return err
	}

	if listener.url.Scheme == "ws" && len(listener.url.Path) == 0 {
		listener.url.Path = "/"
	}

	h.listenersWaitGroup.Add(1)
	INFO.Println("Starting MQTT listener on", listener.url.String())

	go func() {
		<-listener.stop
		INFO.Println("Listener", name, "is stopping...")
		ln.Close()
	}()
	//if this is a WebSocket listener
	if listener.url.Scheme == "ws" {
		var server websocket.Server
		//override the Websocket handshake to accept any protocol name
		server.Handshake = func(c *websocket.Config, req *http.Request) error {
			c.Origin, _ = url.Parse(req.RemoteAddr)
			c.Protocol = []string{"mqtt"}
			return nil
		}
		//set up the ws connection handler, ie what we do when we get a new websocket connection
		server.Handler = func(ws *websocket.Conn) {
			ws.PayloadType = websocket.BinaryFrame
			INFO.Println("New incoming websocket connection", ws.RemoteAddr())
			listener.connections = append(listener.connections, ws)
			h.InitClient(ws)
		}
		//set the path that the http server will recognise as related to this websocket
		//server, needs to be configurable really.
		http.Handle(listener.url.Path, server)
		//ListenAndServe loops forever receiving connections and initiating the handler
		//for each one.
		go func(ln net.Listener) {
			defer h.listenersWaitGroup.Done()
			err := http.Serve(ln, nil)
			if err != nil {
				ERROR.Println(err.Error())
				return
			}
		}(ln)
	} else {
		//loop forever accepting connections and launch InitClient as a goroutine with the connection
		go func() {
			defer h.listenersWaitGroup.Done()
			for {
				conn, err := ln.Accept()
				if err != nil {
					ERROR.Println(err.Error())
					return
				}
				INFO.Println("New incoming connection", conn.RemoteAddr())
				listener.connections = append(listener.connections, conn)
				go h.InitClient(conn)
			}
		}()
	}
	return nil
}
開發者ID:RouGang,項目名稱:hrotti,代碼行數:71,代碼來源:server.go


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