Пример #1
0
func (fl *fakeLoggregator) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fl.receivedRequests = append(fl.receivedRequests, r)
	ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		Fail("Bad Handshake")
		return
	} else if err != nil {
		Fail("Upgrade Close")
		return
	}
	defer ws.Close()

	r.ParseForm()

	for _, msg := range fl.messages {
		ws.WriteMessage(websocket.BinaryMessage, []byte(msg))
	}
	for {
		_, _, err := ws.ReadMessage()

		if err == nil {
			fl.numKeepAlives++
			continue
		}
		return
	}
}
Пример #2
0
func socket(w http.ResponseWriter, r *http.Request) {
	log.Print("connection established")
	if _case == "hang" {
		hang := time.Minute
		log.Printf("hanging for %s\n", hang.String())
		time.Sleep(hang)
	}
	ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if err != nil {
		log.Print(err)
		return
	}
	defer func() {
		ws.Close()
		log.Print("connection closed")
	}()
	for {
		msgt, msg, err := ws.ReadMessage()
		if err != nil {
			log.Print(err)
			return
		}
		log.Print("rcvd: '" + string(msg) + "'")
		ws.WriteMessage(msgt, msg)
	}
}
Пример #3
0
func wsHandler(w http.ResponseWriter, r *http.Request) {

	// Websocket handshake.
	ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(w, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		return
	}

	addr := ws.RemoteAddr()

	log.Printf("Websocket accepted: %s\n", addr)

	// Creating player.
	one := newPlayer(ws)

	// Adding player to sector.
	mainSector.addPlayer(one)

	// Spawing writing goroutine.
	go one.writer()

	// Sending player identification.
	one.ident()

	// Blocking this function on a reader.
	one.reader()

	// Reader has stopped, good bye!
	log.Printf("Websocket finalized: %s", addr)
}
Пример #4
0
func serveWs(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		http.Error(w, "Method not allowed", 405)
		return
	}

	// Read request details.
	r.ParseForm()
	iface := r.FormValue("if")
	if iface == "" {
		iface = "eth0"
	}

	ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(w, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		log.Println(err)
		return
	}
	c := &connection{send: make(chan []byte, 256), ws: ws, iface: iface}
	h.register <- c
	go c.writePump()
	c.readPump()
}
Пример #5
0
func websocketHandler(w http.ResponseWriter, r *http.Request) {

	conn, _ := websocket.Upgrade(w, r, nil, 1024, 1024)
	addConnection(conn)
	listen(conn)

}
Пример #6
0
func wsHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	fmt.Println(r.Method)
	// Taken from gorilla's website
	conn, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(w, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		log.Println(err)
		return
	}
	log.Println("Succesfully upgraded connection")
	connections[conn] = true

	for {
		// Blocks until a message is read
		_, msg, err := conn.ReadMessage()
		if err != nil {
			delete(connections, conn)
			conn.Close()
			return
		}
		log.Println(string(msg))
		sendAll(msg)
	}
}
// Join method handles WebSocket requests for WebSocketController.
func (this *WebSocketController) Join() {
	uname := this.GetString("uname")
	if len(uname) == 0 {
		this.Redirect("/", 302)
		return
	}

	// Upgrade from http request to WebSocket.
	ws, err := websocket.Upgrade(this.Ctx.ResponseWriter, this.Ctx.Request, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(this.Ctx.ResponseWriter, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		beego.Error("Cannot setup WebSocket connection:", err)
		return
	}

	// Join chat room.
	Join(uname, ws)
	defer Leave(uname)

	// Message receive loop.
	for {
		_, p, err := ws.ReadMessage()
		if err != nil {
			return
		}
		publish <- newEvent(models.EVENT_MESSAGE, uname, string(p))
	}
}
Пример #8
0
func serveWs(w http.ResponseWriter, r *http.Request) {
	log.Print("serveWs")
	session, _ := store.Get(r, "session-name")
	if session.IsNew {
		log.Printf("rejecting ws without session from %v",
			r.RemoteAddr)
		return
	}
	ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		log.Printf("rejecting ws with bad handshake from %v",
			r.RemoteAddr)
		http.Error(w, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		log.Printf("serveWs error: %s", err.Error())
		return
	}
	log.Printf("serveWs ws connection from %v", r.RemoteAddr)
	c := &wsconn{send: make(chan []byte, 256), ws: ws}
	h.register <- c
	defer func() { h.unregister <- c }()
	go c.writer()
	c.reader()
}
Пример #9
0
func notificationWSHandler(w http.ResponseWriter, r *http.Request) {
	sid := r.URL.Query()["sid"][0]

	cSession := coditorSessions.get(sid)

	if nil == cSession {
		return
	}

	conn, _ := websocket.Upgrade(w, r, nil, 1024, 1024)
	wsChan := util.WSChannel{Sid: sid, Conn: conn, Request: r, Time: time.Now()}

	ret := map[string]interface{}{"notification": "Notification initialized", "cmd": "init-notification"}
	err := wsChan.WriteJSON(&ret)
	if nil != err {
		return
	}

	notificationWS[sid] = &wsChan

	logger.Tracef("Open a new [Notification] with session [%s], %d", sid, len(notificationWS))

	// add user event handler
	cSession.EventQueue.addHandler(eventHandleFunc(event2Notification))

	input := map[string]interface{}{}

	for {
		if err := wsChan.ReadJSON(&input); err != nil {
			return
		}
	}
}
Пример #10
0
func (h *hub) handleConn(w http.ResponseWriter, r *http.Request) {
	conn, err := websocket.Upgrade(w, r, nil, 0, 0)
	ok(err)
	s := &stream{h: h, conn: conn}

	for {
		_, buf, err := conn.ReadMessage()
		if isReadFromClosedConnError(err) {
			log.Printf("conn closed: %v", err)
			break
		}
		ok(err)
		// TODO: Avoid decoding multiple times.
		var mt MsgType
		ok(json.Unmarshal(buf, &mt))
		switch mt.Type {
		case "SubscribeC2S":
			var msg SubscribeC2S
			ok(json.Unmarshal(buf, &msg))
			ok(s.processSubscribeC2S(&msg))
		case "SubscribeI2R":
			var msg SubscribeI2R
			ok(json.Unmarshal(buf, &msg))
			ok(s.processSubscribeI2R(&msg))
		case "PatchC2S":
			var msg PatchC2S
			ok(json.Unmarshal(buf, &msg))
			ok(s.processPatchC2S(&msg))
		default:
			panic(fmt.Errorf("unknown message type: %s", mt.Type))
		}
	}

	conn.Close()
}
Пример #11
0
func (b BackendController) WsHandler(writer http.ResponseWriter, request *http.Request) {
	conn, err := websocket.Upgrade(writer, request, nil, 1024, 1024)
	log.Println("getting a connection")
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(writer, "got a websocket handshake", 400)
		return
	} else if err != nil {
		log.Println(err)
		return
	}

	b.ConnectionHandler(conn)
	defer b.CleanUpHandler(conn)      // if this function ever exits, clean up the data
	defer delete(b.connections, conn) // if this function ever exits, clean up the data

	b.connections[conn] = true

	for {
		_, msg, err := conn.ReadMessage()
		if err != nil {
			return
		}
		b.EventHandler(msg, conn)
	}
}
Пример #12
0
func (w *WebsocketServer) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	w.logger.Debug("WebsocketServer.ServeHTTP: starting")
	var handler wsHandler
	var err error

	paths := strings.Split(request.URL.Path, "/")
	endpointName := paths[1]

	if endpointName == "firehose" {
		handler, err = w.firehoseHandler(paths, writer, request)
	} else {
		handler, err = w.appHandler(paths, writer, request)
	}

	if err != nil {
		w.logger.Errorf("WebsocketServer.ServeHTTP: %s", err.Error())
		return
	}

	ws, err := gorilla.Upgrade(writer, request, nil, 1024, 1024)
	if err != nil {
		w.logger.Errorf("WebsocketServer.ServeHTTP: Upgrade error (returning 400): %s", err.Error())
		http.Error(writer, err.Error(), 400)
		return
	}

	defer func() {
		ws.WriteControl(gorilla.CloseMessage, gorilla.FormatCloseMessage(gorilla.CloseNormalClosure, ""), time.Time{})
		ws.Close()
	}()

	handler(ws)
}
Пример #13
0
// Upgrade the connection to a websocket connection
func upgradeRequest(resp http.ResponseWriter, req *http.Request, o *Options) (*websocket.Conn, int, error) {
	if req.Method != "GET" {
		o.log("Method %s is not allowed", LogLevelWarning, req.RemoteAddr, req.Method)
		return nil, http.StatusMethodNotAllowed, errors.New("Method not allowed")
	}

	allowedOrigin := replacementRegexp.ReplaceAllString(o.AllowedOrigin, req.Host)
	if r, err := regexp.MatchString(allowedOrigin, req.Header.Get("Origin")); !r || err != nil {
		o.log("Origin %s is not allowed", LogLevelWarning, req.RemoteAddr, req.Host)
		return nil, http.StatusForbidden, errors.New("Origin not allowed")
	}

	o.log("Request to %s has been allowed for origin %s", LogLevelDebug, req.RemoteAddr, req.Host, req.Header.Get("Origin"))

	ws, err := websocket.Upgrade(resp, req, nil, 1024, 1024)
	if handshakeErr, ok := err.(websocket.HandshakeError); ok {
		o.log("Handshake failed: %s", LogLevelWarning, req.RemoteAddr, handshakeErr)
		return nil, http.StatusBadRequest, handshakeErr
	} else if err != nil {
		o.log("Handshake failed: %s", LogLevelWarning, req.RemoteAddr, err)
		return nil, http.StatusBadRequest, err
	}

	o.log("Connection established", LogLevelInfo, req.RemoteAddr)
	return ws, http.StatusOK, nil
}
Пример #14
0
func (w *WebsocketServer) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
	var handler func(string, *gorilla.Conn)

	switch r.URL.Path {
	case TAIL_LOGS_PATH:
		handler = w.streamLogs
	case RECENT_LOGS_PATH:
		handler = w.recentLogs
	case DUMP_LOGS_PATH:
		handler = w.recentLogs
	default:
		http.Error(rw, "invalid path "+r.URL.Path, 400)
		return
	}

	appId, err := w.validate(r)
	if err != nil {
		http.Error(rw, err.Error(), 400)
		return
	}

	ws, err := gorilla.Upgrade(rw, r, nil, 1024, 1024)
	if err != nil {
		http.Error(rw, err.Error(), 400)
		return
	}

	defer ws.Close()
	defer ws.WriteControl(gorilla.CloseMessage, gorilla.FormatCloseMessage(gorilla.CloseNormalClosure, ""), time.Time{})

	handler(appId, ws)
}
Пример #15
0
func (f *fakeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.Method == "HEAD" {
		w.WriteHeader(http.StatusOK)
		return
	}

	if r.Method != "GET" {
		http.Error(w, "Method not allowed", 405)
		return
	}

	ws, err := websocket.Upgrade(w, r, nil, 0, 0)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(w, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		log.Println(err)
		return
	}
	defer ws.Close()
	defer ws.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Time{})
	f.Lock()
	f.lastWSConn = ws
	f.Unlock()

	go ws.ReadMessage()

	for msg := range f.messages {
		if err := ws.WriteMessage(websocket.BinaryMessage, msg); err != nil {
			return
		}
	}
}
Пример #16
0
func slashws(w http.ResponseWriter, req *http.Request) {
	if req.Method != "GET" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}
	if req.Header.Get("Origin") != "http://"+req.Host {
		http.Error(w, "Forbidden", http.StatusForbidden)
		return
	}
	ws, err := websocket.Upgrade(w, req, nil, 1024, 1024)
	if err != nil {
		if _, ok := err.(websocket.HandshakeError); ok {
			http.Error(w, "websocket.Upgrade errd", http.StatusBadRequest)
			return
		}
		panic(err)
	}

	wc := &wclient{ws: ws, ping: make(chan bool, 1)}
	register <- wc
	defer func() {
		unregister <- wc
	}()
	go wc.waitfor_messages() // read from client
	wc.waitfor_updates()     // write to  client
}
Пример #17
0
func (h *sockethub) WsHandler(w http.ResponseWriter, r *http.Request) {
	var authenticated bool

	if h.Auth != nil {
		authenticated = h.Auth(r)
	}

	if authenticated {
		ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)

		if _, ok := err.(websocket.HandshakeError); ok {
			http.Error(w, "Not a websocket handshake", 400)
			return
		} else if err != nil {
			log.Printf("WsHandler error: %s", err.Error())
			return
		}

		c := &connection{send: make(chan *Data), ws: ws}
		h.register <- c

		defer func() { h.unregister <- c }()
		go c.writer()
		c.reader()
	} else {
		http.Error(w, "Invalid API key", 401)
	}
}
Пример #18
0
/* HTTP handler that can be dropped into the standard http handlers list */
func FayeHandler(server faye.Server) http.Handler {
	// websocketHandler := websocket.Handler(transport.WebsocketServer(server))

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Header.Get("Upgrade") == "websocket" {

			ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
			if _, ok := err.(websocket.HandshakeError); ok {
				http.Error(w, "Not a websocket handshake", 400)
				return
			} else if err != nil {
				log.Println(err)
				return
			}

			transport.WebsocketServer(server)(ws)
		} else {
			if r.Method == "POST" {
				var v interface{}
				dec := json.NewDecoder(r.Body)
				if err := dec.Decode(&v); err == nil {
					transport.MakeLongPoll(v, server, w)
				} else {
					log.Fatal(err)
				}
			}
		}
	})
}
Пример #19
0
func (ws *WebServer) wsHandler(w http.ResponseWriter, r *http.Request) {
	conn, err := websocket.Upgrade(w, r, nil, 1024*1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(w, "Not a websocket handshake", http.StatusBadRequest)
		return
	} else if err != nil {
		log.Print(err)
		return
	}

	for {
		messageType, p, err := conn.ReadMessage()
		if err != nil {
			return
		}
		if messageType == websocket.TextMessage {
			msg := string(p)
			parts := strings.Split(msg, ",")
			speedStr, angleStr := parts[0], parts[1]

			_, err = ws.setOrientation(speedStr, angleStr)
			if err != nil {
				log.Print(err)
			}
		}
	}
}
Пример #20
0
// serverWs handles webocket requests from the peer.
func serveWs(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		http.Error(w, "Method not allowed", 405)
		return
	}
	/*
		if r.Header.Get("Origin") != "http://"+r.Host {
			log.Println("403")
			http.Error(w, "Origin not allowed", 403)
			return
		}
	*/
	ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(w, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		log.Println(err)
		return
	}
	c := &connection{send: make(chan []byte, 256), ws: ws}
	h.register <- c
	go c.writePump()
	c.readPump()
}
Пример #21
0
func Handler(w http.ResponseWriter, r *http.Request) {
	c, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if err != nil {
		log.Println(err)
		return
	}

	s := NewSession()

	go func() {
		for m := range s.m {
			if err := c.WriteJSON(m); err != nil {
				if err != io.EOF {
					log.Println(err)
				}
				return
			}
		}
	}()

	for {
		m := new(Message)
		if err := c.ReadJSON(m); err != nil {
			if err != io.EOF {
				log.Println(err)
			}
			return
		}
		if err := s.Handle(m); err != nil {
			log.Println(err)
		}
	}
}
Пример #22
0
func serveWs(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		http.Error(w, "Method not allowed", 405)
		return
	}

	// TODO: Add origin check / CORS support

	ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(w, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		log.Println(err)
		return
	}

	if r.URL.Path == "/ws/v1/data" {
		c := &connection{send: make(chan []byte, 256), ws: ws}
		h.register <- c
		go c.writePump()
	} else if r.URL.Path == "/ws/v1/control" {
		fmt.Println("Got registration")
	}
}
Пример #23
0
func (s *Server) websocketHandler(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	blockId, ok := vars["id"]
	if !ok {
		s.apiWrap(w, r, 500, s.response("must specify block ID to connect"))
		return
	}

	if r.Method != "GET" {
		http.Error(w, "Method not allowed", 405)
		return
	}
	w.Header().Set("Access-Control-Allow-Origin", "*")
	/*if r.Header.Get("Origin") != "http://"+r.Host {
		http.Error(w, "Origin not allowed", 403)
		return
	}*/
	ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		s.apiWrap(w, r, 500, s.response("Not a websocket handshake"))
		return
	} else if err != nil {
		//log.Println(err)
		return
	}
	c := &connection{send: make(chan []byte, 256), ws: ws}

	s.manager.Mu.Lock()
	blockChan, connId, err := s.manager.GetSocket(vars["id"])
	s.manager.Mu.Unlock()

	if err != nil {
		s.apiWrap(w, r, 500, s.response(err.Error()))
		return
	}

	ticker := time.NewTicker((10 * time.Second * 9) / 10)
	go func(c *connection, bChan chan *blocks.Msg, cId string, bId string) {
		defer func() {
			s.manager.Mu.Lock()
			_ = s.manager.DeleteSocket(bId, cId)
			s.manager.Mu.Unlock()
			ticker.Stop()
			c.ws.Close()
		}()
		for {
			select {
			case msg := <-bChan:
				message, _ := json.Marshal(msg.Msg)
				if err := c.write(websocket.TextMessage, message); err != nil {
					return
				}
			case <-ticker.C:
				if err := c.write(websocket.PingMessage, []byte{}); err != nil {
					return
				}
			}
		}
	}(c, blockChan, connId, blockId)
}
Пример #24
0
// wsHandler eleva la conexio http con el cliente a websockets
func wsHandler(w http.ResponseWriter, r *http.Request) {
	conn, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(w, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		log.Println(err)
		return
	}
	defer conn.Close()

	var data struct {
		UserName string `json:"userName"`
		UID      int32  `json:"uid"`
	}
	if err := conn.ReadJSON(&data); err != nil {
		log.Fatal(err)
		return
	}
	if p, ok := players[data.UID]; ok {
		p.Conn = conn
		log.Println("El jugador con uid", data.UID, "inició conexión websocket")
	} else {
		log.Println("EL jugador con uid", data.UID, "no tiene sesión iniciada")
		return
	}
}
Пример #25
0
func socketHandler(w http.ResponseWriter, r *http.Request) {
	conn, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(w, "go home, you're not a socket, you're drunk", 400)
		return
	} else if err != nil {
		log.Println(err)
		return
	}

	log.Println("new client")
	defer log.Println("client closed")

	conn.WriteMessage(websocket.TextMessage, []byte("hello"))

	// TODO: handle timing out; don't want to have these linger
	for {
		typ, msg, err := conn.ReadMessage()
		log.Println(string(msg))

		if err != nil {
			return
		}
		if err := conn.WriteMessage(typ, msg); err != nil {
			return
		}
	}
}
Пример #26
0
func socketHandler(w http.ResponseWriter, r *http.Request) {
	c, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if err != nil {
		log.Println(err)
		return
	}

	u, err := ui.New()
	if err != nil {
		log.Println(err)
		return
	}
	defer u.Close()

	go func() {
		for m := range u.M {
			if err := c.WriteJSON(m); err != nil {
				log.Println(err)
				return
			}
		}
	}()

	for {
		m := new(ui.Message)
		if err := c.ReadJSON(m); err != nil {
			log.Println(err)
			return
		}
		if err := u.Handle(m); err != nil {
			log.Println(err)
		}
	}
}
Пример #27
0
// WSHandler handles request of creating editor channel.
// XXX: NOT used at present
func WSHandler(w http.ResponseWriter, r *http.Request) {
	httpSession, _ := session.HTTPSession.Get(r, "wide-session")
	if httpSession.IsNew {
		http.Error(w, "Forbidden", http.StatusForbidden)

		return
	}

	sid := httpSession.Values["id"].(string)

	conn, _ := websocket.Upgrade(w, r, nil, 1024, 1024)
	editorChan := util.WSChannel{Sid: sid, Conn: conn, Request: r, Time: time.Now()}

	ret := map[string]interface{}{"output": "Editor initialized", "cmd": "init-editor"}
	err := editorChan.WriteJSON(&ret)
	if nil != err {
		return
	}

	session.EditorWS[sid] = &editorChan

	logger.Tracef("Open a new [Editor] with session [%s], %d", sid, len(session.EditorWS))

	args := map[string]interface{}{}
	for {
		if err := session.EditorWS[sid].ReadJSON(&args); err != nil {
			return
		}

		code := args["code"].(string)
		line := int(args["cursorLine"].(float64))
		ch := int(args["cursorCh"].(float64))

		offset := getCursorOffset(code, line, ch)

		logger.Tracef("offset: %d", offset)

		gocode := util.Go.GetExecutableInGOBIN("gocode")
		argv := []string{"-f=json", "autocomplete", strconv.Itoa(offset)}

		var output bytes.Buffer

		cmd := exec.Command(gocode, argv...)
		cmd.Stdout = &output

		stdin, _ := cmd.StdinPipe()
		cmd.Start()
		stdin.Write([]byte(code))
		stdin.Close()
		cmd.Wait()

		ret = map[string]interface{}{"output": string(output.Bytes()), "cmd": "autocomplete"}

		if err := session.EditorWS[sid].WriteJSON(&ret); err != nil {
			logger.Error("Editor WS ERROR: " + err.Error())
			return
		}
	}
}
func makeTestHandler(keepAliveCompleted chan struct{}) http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		conn, _ := websocket.Upgrade(rw, req, nil, 0, 0)
		go conn.ReadMessage()
		server.NewKeepAlive(conn, 50*time.Millisecond).Run()
		close(keepAliveCompleted)
	})
}
Пример #29
0
func upgrade(w http.ResponseWriter, r *http.Request) *websocket.Conn {
	ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if err != nil {
		http.Error(w, "Not a websocket handshake", 400)
		return nil
	}
	return ws
}
Пример #30
0
func (this *Server) initSocketListener() {
	Connect := func(w http.ResponseWriter, r *http.Request) {
		if r.Method != "GET" {
			http.Error(w, "Method not allowed", 405)
			return
		}
		//if r.Header.Get("Origin") != "http://"+r.Host {
		//        http.Error(w, "Origin not allowed", 403)
		//        return
		// }

		ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
		if _, ok := err.(websocket.HandshakeError); ok {
			http.Error(w, "Not a websocket handshake", 400)
			return
		} else if err != nil {
			log.Println(err)
			return
		}

		defer func() {
			ws.Close()
			if DEBUG {
				log.Println("Socket Closed")
			}
		}()

		sock := newSocket(ws, nil, this, "")

		if DEBUG {
			log.Printf("Socket connected via %s\n", ws.RemoteAddr())
		}
		if err := sock.Authenticate(""); err != nil {
			if DEBUG {
				log.Printf("Error: %s\n", err.Error())
			}
			return
		}

		go sock.listenForMessages()
		go sock.listenForWrites()

		if this.timeout <= 0 { // if timeout is 0 then wait forever and return when socket is done.
			<-sock.done
			return
		}

		select {
		case <-time.After(this.timeout * time.Second):
			sock.Close()
			return
		case <-sock.done:
			return
		}
	}

	http.HandleFunc("/socket", Connect)
}