Example #1
0
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}
	}
}
Example #2
0
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
			}
		}
	}
}
Example #3
0
/*
 * 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}
	}
}
Example #4
0
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)
		}
	}
}
Example #5
0
// 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()
}
Example #6
0
func IsClosed(ws *websocket.Conn) bool {
	var ibuff [50]byte

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

	return false
}
Example #7
0
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
		}
	}
}
Example #8
0
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()
}
Example #9
0
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()
}
Example #10
0
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
	}
}
Example #11
0
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))
	}
}
Example #12
0
/*
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
		}
	}
}
Example #13
0
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]
	}
}
Example #14
0
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
		}
	}
}
Example #15
0
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
		}
	}
}
Example #16
0
func WebSocketServer(ws *websocket.Conn) {
	fmt.Println("WebSocketServer")
	var msg [1024]byte
	ch := CreateReadChannel(ws, msg[:])
	interval := time.Tick(5 * 1e9)
Loop:
	for {
		select {
		case n := <-ch:
			if n == 0 {
				fmt.Println("The connection was closed by peer.")
				break Loop
			}
			ws.Write(msg[:n])
		case _ = <-interval:
			ws.Write([]byte("An interval event fired in a server side."))
		}
	}
}
Example #17
0
func indexHandler(ws *websocket.Conn) {
	var ibuff [50]byte

	i, err := ws.Read(ibuff[0:50])
	if err != nil {
		fmt.Printf("WebSocket error: " + err.String())
		return
	}

	msg := string(ibuff[0:i])
	idx := strings.Index(msg, "!")
	if idx < 0 {
		fmt.Printf("Salt not found\n")
		return
	}

	idstr := msg[0:idx]
	salt := msg[idx+1:]

	uid, err := strconv.Atoui64(idstr)
	if err != nil {
		fmt.Printf("User ID invalid\n")
		return
	}

	defer UnlinkUser(uid, ws)

	usr := LinkUser(uid, salt, ws)
	if usr == nil {
		fmt.Printf("Cannot link with User ID\n")
		return
	}

	for usr.exit == false {
		time.Sleep(1e8)

		if IsClosed(ws) {
			break
		}
	}
}
Example #18
0
func SocketServer(ws *websocket.Conn) {
	c := make(chan []byte, 100)
	e := ws_channels.PushBack(c)
	fmt.Printf("New connection:    %v total\n", ws_channels.Len())
	var data []byte
	for {
		select {
		case data = <-c:
		case <-time.After(5e9): // make sure we're still connected
			data = []byte("")
		}

		if _, err := ws.Write(data); err != nil {
			// fmt.Println("Closing")
			ws.Close()
			break
		}
	}
	ws_channels.Remove(e)
	fmt.Printf("Closed connection: %v total\n", ws_channels.Len())
}
Example #19
0
func wsHandler(ws *websocket.Conn) {
	defer func() {
		unsubscribe(ws)
		ws.Close()
	}()

	subscribe(ws)

	for { // loop forEVER
		var data message
		err := websocket.JSON.Receive(ws, &data)
		if err != nil {
			log.Print("wsHandler > websocket.JSON.Receive: " + err.Error())
			break
		}
		if data.Channel != "" {
			setChannel(ws, data.Channel)
		} else {
			throwFatal(ws, "Must specify a Channel name")
		}
		if data.Auth.User != "" {
			log.Print(data.Auth)
			auth, err := checkAPIAuth(data.Auth.User, data.Auth.Secret)
			if err != nil {
				throwFatal(ws, "Server error. Please try again later.")
			} else {
				if auth {
					if device := strings.Split(data.Channel, "/"); device[0] != data.Auth.User {
						throwFatal(ws, "Unauthorised use of device.")
					} else {
						authorise(ws, data.Auth.User, data.Auth.Secret)
						messageChan <- data
					}
				} else {
					throwFatal(ws, "Auth parameters invalid.")
				}
			}
		}
	}
}
Example #20
0
func doEventStream(ws *websocket.Conn) {
	defer func() {
		subscriptionChan <- subscription{ws, false}
		ws.Close()
	}()

	subscriptionChan <- subscription{ws, true}

	for {
		buf := make([]byte, 512)

		n, err := ws.Read(buf)
		if err != nil {
			log.Println("Error reading from websocket connection")
			break
		}

		messageChan <- message{
			ws,
			buf[0:n],
		}
	}
}
Example #21
0
func liveReload16ConnectionHandler(ws *websocket.Conn) {
	defer func() {
		subscriptionChannel <- subscriptionMessage{ws, false, ""}
		fmt.Printf("Browser disconnected")
		ws.Close()
	}()

	websocket.Message.Send(ws, fmt.Sprintf("!!ver:%s", API_VERSION))
	fmt.Printf("Browser Connected")

	// on connection it's the client url
	var onConnectionMessage string
	websocket.Message.Receive(ws, &onConnectionMessage)
	subscriptionChannel <- subscriptionMessage{ws, true, onConnectionMessage}
	fmt.Printf("Browser URL: %s", onConnectionMessage)

	// websocket messages from the clients get pushed though the eventhub
	for {
		var msg string
		websocket.Message.Receive(ws, &msg)
		messageChannel <- msg
	}
}
Example #22
0
func broadcastHandler(ws *websocket.Conn) {
	defer func() {
		subscriptionChan <- subscription{ws, false}
		ws.Close()
		fmt.Printf("Closed \n")
	}()

	fmt.Printf("Adding to subscription \n")

	subscriptionChan <- subscription{ws, true}
	fmt.Printf("Added to subscription \n")

	buf := make([]byte, 256)
	for {
		n, err := ws.Read(buf)
		fmt.Printf("Reding message %v \n", n)

		if err != nil {
			break
		}
		messageChan <- buf[0:n]
	}
}
Example #23
0
func wssServe(ws *websocket.Conn) {
	fmt.Println("Socket connect")
	ws.Write([]byte(strconv.Itoa(int(*state))))
	b := make([]byte, 2)
	var quit bool
	for !quit {
		ws.Read(b)
		t, _ := strconv.Atoi(string(b))
		fmt.Println(t)
		switch t {
		case 0:
			func() {
				fmt.Println("Server Init")
				if *state > 0 {
					ws.Write([]byte(strconv.Itoa(int(*state))))
				} else {
					ws.Write([]byte("0"))
					b = make([]byte, 5)
					ws.Read(b)
					world, _ := strconv.Atob(string(b))
					fmt.Println(world)
					if world {

					} else {

					}
				}
			}()
		default:
			func() {
				fmt.Println(string(b))
				quit = true
			}()
		}
		quit = true
	}
}
Example #24
0
func (m *model) subscribe(s *websocket.Conn) {
	data, err := json.MarshalIndent(newConnectMessage(m.Changes, m.Kittens, m.VersionIdentifier), "", "  ")
	if err != nil {
		s.Close()
		return
	}

	_, err = s.Write(data)
	if err != nil {
		s.Close()
		return
	}

	m.Conns[s] = 1
}
Example #25
0
func doEventStream(ws *websocket.Conn) {
	ID := chat.UUID()
	defer func() {
		subscriptionChan <- &Subscription{ws, chat.REMOVE_CONNECTION, &User{ID, nil, ""}}
		ws.Close()
	}()

	subscriptionChan <- &Subscription{ws, chat.ADD_CONNECTION, &User{ID, nil, ""}}
	newStartMessage, _ := json.Marshal(
		MessageData{
			"start",
			map[string]interface{}{
				"ID": ID,
			}})

	ws.Write(newStartMessage)

	for {
		buf := make([]byte, 1024)

		n, err := ws.Read(buf)
		if err != nil {
			log.Println("Error reading from websocket connection: ", err.Error())
			break
		}

		newMessageData := new(MessageData)
		err = json.Unmarshal(buf[0:n], newMessageData)

		if err != nil {
			log.Println("Error unmarshaling message: ", string(buf[0:n]), " : ", err.Error())
		}

		messageChan <- message{
			ws,
			*newMessageData,
		}
	}
}
Example #26
0
/*
 * Process image
 */
func process(input *ProcessInput, conn *websocket.Conn, stopCh chan bool) os.Error {
	log.Println(input)

	// open input file
	inputFile, err := os.OpenFile(UploadDir+input.Image, os.O_RDONLY, 0666)
	if err != nil {
		return err
	}
	defer inputFile.Close()

	// create output file
	outputFile, err := os.OpenFile(ResultDir+input.Image, os.O_CREATE|os.O_WRONLY, 0666)
	if err != nil {
		return err
	}
	defer outputFile.Close()

	// decode png image
	inputImage, _, err := image.Decode(inputFile)
	if err != nil {
		return err
	}
	rgbaInput := rgba(inputImage)

	sivqParams := SIVQParameters{
		GammaAdjustment: float(input.GammaAdjust),
		AverageBias:     float(input.AverageBias),
		RotationStride:  float(input.RotationStride),
		MatchingStride:  input.MatchStride,
		MatchingOffset:  input.MatchingOffset,
		Threshold:       float(input.Threshold),
		ProgressCallback: func(p float) {
			conn.Write([]byte(strconv.Ftoa32(float32(p), 'f', 4)))
		},
		StopCh: stopCh}

	// get vector
	var ringVector *RingVector
	if len(input.VectorName) == 0 {
		vectorParams := RingVectorParameters{
			Radius:    input.VectorRadius,
			Count:     input.VectorRings,
			RadiusInc: input.RingSizeInc}

		ringVector = NewRingVector(vectorParams)
		ringVector.LoadData(rgbaInput, input.VecX, input.VecY)
	} else {
		// load vector from file
		vectorFile, err := os.OpenFile(VectorDir+input.VectorName, os.O_RDONLY, 0666)
		if err != nil {
			return err
		}
		defer vectorFile.Close()

		decoder := gob.NewDecoder(vectorFile)
		err = decoder.Decode(&ringVector)
		if err != nil {
			return err
		}
	}

	// do the magic
	outputImage := SIVQ(sivqParams, rgbaInput, ringVector)

	if err = png.Encode(outputFile, outputImage); err != nil {
		return err
	}
	return nil
}
Example #27
0
func (m *model) unsubscribe(s *websocket.Conn) {
	s.Close()
	m.Conns[s] = 0, false
}
func TestAllTheThings(t *testing.T) {
	var ws *websocket.Conn
	var req net.Conn
	var wss [5]*websocket.Conn

	ws = websocketDial(t)
	testWebsocketConnect(t, ws)
	testWebsocketBadRequests(t, ws)
	testWebsocketAuthenticationWithoutToken(t, ws)
	testWebsocketAuthenticationWithInvalidTokenFormat(t, ws)
	testWebsocketAuthenticationWithInvalidToken(t, ws)
	testWebsocketAuthenticationWithValidToken(t, ws)
	testWebsocketSubscribeWithoutChannelName(t, ws)
	testWebsocketSubscribeWithEmptyChannelName(t, ws)
	testWebsocketSubscribeWithInvalidChannelName(t, ws)
	testWebsocketSubscribeToNotExistingChannel(t, ws)
	testWebsocketUnsubscribeWithoutChannelName(t, ws)
	testWebsocketUnsubscribeWithEmptyChannelName(t, ws)
	testWebsocketUnsubscribeWithInvalidChannelName(t, ws)
	testWebsocketUnsubscribeNotSubscribedChannel(t, ws)
	ws.Close()

	ws = websocketDial(t)
	testWebsocketConnect(t, ws)
	testWebsocketSubscribeToPublicChannel(t, ws)
	testWebsocketUnsubscribeSubscribedChannel(t, ws)
	testWebsocketSubscribeToPrivateChannelWithoutAuthentication(t, ws)
	testWebsocketSubscribeToPresenceChannelWithoutAuthentication(t, ws)
	testWebsocketAuthenticationWithValidToken(t, ws)
	testWebsocketSubscribeToPrivateChannelWithAuthentication(t, ws)
	testWebsocketSubscribeToPresenceChannelWithAuthentication(t, ws)
	ws.Close()

	for i := range wss {
		wss[i] = websocketDial(t)
		testWebsocketConnect(t, wss[i])
		testWebsocketAuthenticationWithValidToken(t, wss[i])
	}
	testWebsocketPresenceChannelSubscribeBehaviour(t, wss[:])
	testWebsocketPresenceChannelUnsubscribeBehaviour(t, wss[:])
	for i := range wss {
		wss[i].Close()
		wss[i] = nil
	}

	ws = websocketDial(t)
	testWebsocketConnect(t, ws)
	testWebsocketBroadcastWithoutChannelSpecified(t, ws)
	testWebsocketBroadcastWithEmptyChannelSpecified(t, ws)
	testWebsocketBroadcastWithoutEventSpecified(t, ws)
	testWebsocketBroadcastToNotSubscribedChannel(t, ws)
	testWebsocketBroadcastToNotExistingChannel(t, ws)
	ws.Close()

	for i := range wss {
		wss[i] = websocketDial(t)
		testWebsocketConnect(t, wss[i])
		testWebsocketSubscribeToPublicChannel(t, wss[i])
	}
	testWebsocketBroadcast(t, wss[:])
	testBackendBroadcast(t, req, wss[:])
	for i := range wss {
		wss[i].Close()
		wss[i] = nil
	}

	testBackendBadRequest(t, req)
	testBackendBadIdentity(t, req)
	testBackendOpenChannelWithoutName(t, req)
	testBackendOpenChannelWithInvalidName(t, req)
	testBackendOpenExistingChannel(t, req)
	testBackendOpenNewChannel(t, req)
	testBackendCloseChannelWithoutName(t, req)
	testBackendCloseChannelWithInvalidName(t, req)
	testBackendCloseNotExistingChannel(t, req)
	testBackendRequestSingleAccessTokenWithoutPermission(t, req)
	testBackendRequestSingleAccessTokenWithInvalidPermission(t, req)
	testBackendRequestSingleAccessTokenWithValidPermission(t, req)
	testBackendBroadcastWithEmptyChannelName(t, req)
	testBackendBroadcastWithEmptyEventName(t, req)
	testBackendBroadcastToNotExistingChannel(t, req)
	testBackendBroadcastWithInvalidData(t, req)
}