Esempio n. 1
0
func remoteControl(ws *websocket.Conn) {
	pptRequest := &pptctrl.Request{Response: make(chan string)}

	defer ws.Close()
	defer close(pptRequest.Response)

	r := bufio.NewReader(ws)

	for {
		data, err := r.ReadBytes('\n')
		fmt.Printf("%s", data)

		if err != nil {
			fmt.Printf("Error occured: %s\n", err.Error())
			break
		}

		switch data[0] {
		case '!': // PowerPoint control
			pptRequest.Data = data

			pptctrl.SendRequest(pptRequest)

			// block current goroutine
			extraReturnInfo := <-pptRequest.Response

			if len(extraReturnInfo) > 0 {
				sendPowerPointExtraReturnInfo(data, extraReturnInfo, ws)
			}
		}
	}
}
Esempio n. 2
0
//websocket main handler
func wsMain(ws *websocket.Conn) {
	defer ws.Close()

	wsCtx := newWSContext(ws)

	var msg string
	for {
		//read message
		err := websocket.Message.Receive(ws, &msg)
		if err != nil {
			break
		}
		log.Debug("[wsMain]endpoint's msg = " + msg)

		//parse message
		wsMsg, err := NewEndptMsgFromStr(msg)

		if err != nil {
			log.Error("[wsMain]failed to unmarshal json :" + err.Error())
			continue
		}
		wsCtx.UserID = wsMsg.UserID

		if wsMsg.Domain == "irc" && wsCtx.LoggedIn {
			ClientDoIRCCmd(wsMsg, ws)
		} else {
			dispatchBoksHandler(wsCtx, wsMsg)
		}
	}

	if wsCtx.LoggedIn {
		UserLogout(wsCtx.UserID, ws)
	}
	log.Debug("[wsMain]endpoint exited")
}
Esempio n. 3
0
func readMsg(conn *websocket.Conn, owner string) {
	tmp := make([]byte, 32)
	buf := make([]byte, 0)
	for {
		readlen, err := conn.Read(tmp)
		if err != nil {
			break
		}

		buf = append(buf, tmp[0:readlen]...)
		lensep := strings.Index(string(buf), ":")
		if lensep < 0 {
			continue
		}

		msglen, err := strconv.Atoi(string(buf[0:lensep]))
		if err != nil {
			log.Println("error: ", err)
			break
		}

		if len(buf) < msglen+lensep+1 {
			continue
		}

		msg := Msg{owner, make([]byte, msglen)}
		copy(msg.data, buf[lensep+1:msglen+lensep+1])
		read <- msg
		buf = buf[lensep+msglen+1:]
	}
}
Esempio n. 4
0
func wsHandler(ws *wbs.Conn) {
	defer ws.Close()

	log.Println("Websocket connection recieved.")
	log.Println("Handeling user.")
	handleUser(ws)
}
func (fh *FakeHandler) handle(conn *websocket.Conn) {
	fh.call()
	request := conn.Request()
	fh.setLastURL(request.URL.String())
	fh.setAuthHeader(request.Header.Get("Authorization"))

	if fh.messageReceived != nil {
		go func() {
			for {
				buffer := make([]byte, 1024)
				_, err := conn.Read(buffer)

				if err == nil {
					fh.messageReceived <- true
				} else {
					break
				}
			}
		}()
	}

	for _, protoMessage := range fh.Messages {
		if protoMessage == nil {
			conn.Write([]byte{})
		} else {
			message, err := proto.Marshal(protoMessage)
			Expect(err).ToNot(HaveOccurred())

			conn.Write(message)
		}
	}

	<-fh.closeConnection
	conn.Close()
}
Esempio n. 6
0
func connect(conn *websocket.Conn) {
	logger.Printf("websocket from %s", conn.RemoteAddr())
	defer conn.Close()
	var form []byte
	var f Form
	if err := websocket.Message.Receive(conn, &form); err != nil {
		return
	}
	if err := json.Unmarshal(form, &f); err != nil {
		loggedmessage(conn, "invalid request: %s (%s)", form, err)
		return
	}
	loggedmessage(conn, "opening connection to %s for %s", f.Serv, f.Nick)
	client, err := NewClient(f.Serv, f.Nick)
	if err != nil {
		websocket.Message.Send(conn, "connection error: "+err.Error())
		return
	}
	defer func() {
		logger.Printf("closing connection to %s for %s", f.Serv, f.Nick)
		websocket.Message.Send(conn, "connection closed.")
		client.Cmd("QUIT :%s", "client left.")
		client.Close()
	}()
	logger.Printf("joining channel %s", f.Chan)
	client.Cmd("JOIN %s", f.Chan)
	for line := range client.lines {
		// send {"system": message} or {"line": message}
		websocket.JSON.Send(conn, line)
	}
}
Esempio n. 7
0
func (proxy *Proxy) HandleWebSocket(clientWS *websocket.Conn) {
	req := clientWS.Request()
	req.ParseForm()
	req.Form.Get("app")
	clientAddress := clientWS.RemoteAddr()

	appId := req.Form.Get("app")

	extractAuthTokenFromUrl := func(u *url.URL) string {
		authorization := ""
		queryValues := u.Query()
		if len(queryValues["authorization"]) == 1 {
			authorization = queryValues["authorization"][0]
		}
		return authorization
	}

	authToken := clientWS.Request().Header.Get("Authorization")
	if authToken == "" {
		authToken = extractAuthTokenFromUrl(req.URL)
	}

	if authorized, errorMessage := proxy.isAuthorized(appId, authToken, clientAddress); !authorized {
		data, err := proto.Marshal(errorMessage)
		if err != nil {
			proxy.logger.Errorf("Error marshalling log message: %s", err)
		}
		websocket.Message.Send(clientWS, data)
		clientWS.Close()
		return
	}

	defer clientWS.Close()

	proxy.logger.Debugf("Output Proxy: Request for app: %v", req.Form.Get("app"))
	serverWSs := make([]*websocket.Conn, len(proxy.hashers))
	for index, hasher := range proxy.hashers {
		proxy.logger.Debugf("Output Proxy: Servers in group [%v]: %v", index, hasher.LoggregatorServers())

		server := hasher.GetLoggregatorServerForAppId(appId)
		proxy.logger.Debugf("Output Proxy: AppId is %v. Using server: %v", appId, server)

		config, err := websocket.NewConfig("ws://"+server+req.URL.RequestURI(), "http://localhost")

		if err != nil {
			proxy.logger.Errorf("Output Proxy: Error creating config for websocket - %v", err)
		}

		serverWS, err := websocket.DialConfig(config)
		if err != nil {
			proxy.logger.Errorf("Output Proxy: Error connecting to loggregator server - %v", err)
		}

		if serverWS != nil {
			serverWSs[index] = serverWS
		}
	}
	proxy.forwardIO(serverWSs, clientWS)

}
Esempio n. 8
0
func newClient(ws *websocket.Conn, h *hub, srv *wsServer) *wsClient {
	if ws == nil {
		log.Panicln("ws cannot be nil")
	}

	if srv == nil {
		log.Panicln("server cannot be nil")
	}

	maxID++

	return &wsClient{
		id:   maxID,
		ws:   ws,
		h:    h,
		srv:  srv,
		subs: make(map[string]string),

		inMsgChan:  make(chan *wsMessage),
		outMsgChan: make(chan *wsMessage),
		doneChan:   make(chan bool),

		socketID: sha1Sum(fmt.Sprintf("%s-%s-%d", ws.RemoteAddr().String(),
			ws.LocalAddr().String(), maxID)),
	}
}
Esempio n. 9
0
// Starting point of websocket connection
//	*	Verify identity
//	*	Register send/recieve channel
//	* 	Manage send/recieve for duration of connection
func (t *Server) HandleWebsocket(conn *websocket.Conn) {
	defer conn.Close() //Close connection at end of this function

	//Register Connection
	c, err := t.registerConnection(conn)
	if err != nil {
		log.Error("postmaster: error registering connection: %s", err)
		return
	}

	//Setup goroutine to send all message on chan
	go func() {
		for msg := range c.out {
			log.Trace("postmaster: sending message: %s", msg)
			err := websocket.Message.Send(conn, msg)
			if err != nil {
				log.Error("postmaster: error sending message: %s", err)
			}
		}
	}()

	//Setup message recieving (Blocking for life of connection)
	t.recieveOnConn(c, conn)

	//Call disconnection method
	//FIXME Figure out why pendingAuth is nil sometimes
	if t.OnDisconnect != nil && c.pendingAuth != nil {
		t.OnDisconnect(c.pendingAuth.authKey, c.pendingAuth.authExtra)
	}

	//Unregister connection
	delete(t.connections, c.id)
}
Esempio n. 10
0
// Connection handler. This function called after new client
// connected to websocket server.
// Also this method performs register user - client must send valid apiKey
// to receive messages from redis.
func wsHandler(ws *websocket.Conn) {
	log.Println("New client")
	defer ws.Close()
	// websocket.Message.Send(ws, "Hello dear user!")

	for {
		// Message received from client
		var message string

		// Read messages from client
		// Code blocks here, after any message received
		// will resume execution.
		if err := websocket.Message.Receive(ws, &message); err != nil {
			log.Println("Error receiving message. Closing connection.")
			return
		}

		// Register user
		// TODO: Cache user
		user, _ := common.FindUserByApiKey(message)
		if user != nil {
			log.Println("Registering apiKey", user.ApiKey)
			clients[user.ApiKey] = ws
		} else {
			log.Println("Error registering user", message)
		}
	}
}
Esempio n. 11
0
func (gs *gameServer) clientListenRead(ws *websocket.Conn) {
	defer func() {
		ws.Close()
	}()

	for {
		select {
		default:
			var move util.ClientMove
			err := websocket.JSON.Receive(ws, &move)
			if err == io.EOF {
				return
				// EOF!
			} else if err != nil {
				LOGE.Println(err)
			} else {
				var dir lib2048.Direction
				switch move.Direction {
				case 0:
					dir = lib2048.Up
				case 1:
					dir = lib2048.Right
				case 2:
					dir = lib2048.Down
				case 3:
					dir = lib2048.Left
				}
				LOGV.Println("Received", dir, "from web client")
				move := lib2048.NewMove(dir)
				gs.clientMoveCh <- move
			}
		}
	}
}
Esempio n. 12
0
// WebSocket server to handle chat between clients
func SockServer(ws *websocket.Conn) {
	var err error
	var clientMessage string
	// use []byte if websocket binary type is blob or arraybuffer
	// var clientMessage []byte

	// cleanup on server side
	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))

	updateNewClient(sockCli)
	// for loop so the websocket stays open otherwise
	// it'll close after one Receive
	for {
		if err = Message.Receive(ws, &clientMessage); err != nil {
			// If we cannot Read then the connection is closed
			log.Println("Websocket Disconnected waiting", err.Error())
			// remove the ws client conn from our active clients
			delete(ActiveClients, sockCli)
			log.Println("Number of clients still connected ...", len(ActiveClients))
			return
		}
		piano_ctrl <- clientMessage
	}
}
Esempio n. 13
0
func transmitter(id string, ws *websocket.Conn, c chan *registrar.T, ctx context.Context, cancel context.CancelFunc) {
	var err error
	var data *registrar.T
	defer ws.Close()
	//defer close(c)
	defer cancel()
	defer registrar.RemoveConnection(id)
Loop:
	for {
		select {
		case data = <-c:
			err = websocket.JSON.Send(ws, *data)
			//websocket.Message.Send(ws, data.Msg)
			if err != nil {
				if !ws.IsClientConn() {
					log.Printf("transmitter closed\n")
				} else {
					log.Printf("transmitter error %v\n", err)
				}
				break Loop
			}
		case <-ctx.Done():
			log.Printf("transmitter closed")
			break Loop
		}
	}
}
Esempio n. 14
0
//Function that handles all the request and creates response
func WShandler(ws *websocket.Conn) {
	var err error

	// cleanout
	defer ws.Close()
	//Here we are creating list of clients that gets connected
	socketClientIP := ws.Request().RemoteAddr
	socketClient := Clients{ws, socketClientIP}
	ActiveClients[socketClient] = 0
	log.Println("Total clients live:", len(ActiveClients))
	//For loop to keep it open, It closes after one Send/Recieve
	for {
		var reply string
		var clientMessage string
		if err = websocket.Message.Receive(ws, &reply); err != nil {
			log.Println("Can't receive ", socketClientIP, err.Error())
		}
		fmt.Println("Received back from client: " + reply)

		clientMessage = socketClient.IP + " : " + reply
		//ForEACH client conected, send back the msg to everyone
		for cs, _ := range ActiveClients {
			if err = websocket.Message.Send(cs.websocket, clientMessage); err != nil {
				// It could not send message to a peer
				log.Println("Could not send message to ", cs.IP, err.Error())
			}
		}
	}
}
func handleConnection(conn *net.TCPConn) error {
	defer conn.Close()

	handlerChan <- 1
	defer func() {
		handlerChan <- -1
	}()

	var ws *websocket.Conn

	conn.SetDeadline(time.Now().Add(socksTimeout))
	err := AwaitSocks4aConnect(conn, func(dest string) (*net.TCPAddr, error) {
		// Disable deadline.
		conn.SetDeadline(time.Time{})
		Log("SOCKS request for %s", dest)
		destAddr, err := net.ResolveTCPAddr("tcp", dest)
		if err != nil {
			return nil, err
		}
		wsUrl := url.URL{Scheme: "ws", Host: dest}
		ws, err = websocket.Dial(wsUrl.String(), "", wsUrl.String())
		if err != nil {
			return nil, err
		}
		Log("WebSocket connection to %s", ws.Config().Location.String())
		return destAddr, nil
	})
	if err != nil {
		return err
	}
	defer ws.Close()
	proxy(conn, ws)
	return nil
}
Esempio n. 16
0
File: main.go Progetto: ziutek/de
func data(w *websocket.Conn) {
	defer w.Close()

	min := matrix.NewDense(1, 4, 4, Min()...)
	max := matrix.NewDense(1, 4, 4, Max()...)
	m := de.NewMinimizer(cost, 20, min, max)
	points := make([][2]int, len(m.Pop))
	for {
		minCost, maxCost := m.NextGen()
		// Transform agents in 4D space to points on 2D image
		for i, a := range m.Pop {
			points[i][0], points[i][1] = D4toD2(a.X.Elems())
		}
		// Send points to the browser
		if err := websocket.JSON.Send(w, points); err != nil {
			e, ok := err.(*net.OpError)
			if !ok || e.Err != syscall.EPIPE && e.Err != syscall.ECONNRESET {
				log.Print(err)
			}
			return
		}
		// Check the end condition
		sum := math.Abs(minCost) + math.Abs(maxCost)
		diff := math.Abs(maxCost - minCost)
		if diff/(sum+2*math.SmallestNonzeroFloat64) < 1e-4 {
			return
		}
		// Slow down calculations for better presentation
		time.Sleep(100 * time.Millisecond)
	}
}
Esempio n. 17
0
func (s *OctopusSocket) handleControlConn(conn *websocket.Conn) {
	defer conn.Close()
	defer s.device.Disengage() // TODO: this will kill the device on multiple conns

	uuid, _ := Uuid()
	session := &SocketSession{
		conn:      conn,
		pairingId: uuid,
		device:    s.device, // in the future we can instantiate device based on message
		pps:       s.pps,
		batchSize: s.batchSize,
		kickoff:   s.kickoff,
		recorder:  NewDeviceRecorder(s.device, NewObfRecorder(s.device.Repo())),
	}
	log.Printf("got session: %+v", session)
	// keep processing as long as we are connected
	for {
		msgBytes, msgBase, err := Receive(conn)
		if err != nil {
			if err == io.EOF || err.Error() == "EOF" {
				break
			}
			continue
		}
		log.Printf("Octopus Socket: RECEIVED %s", msgBytes)
		session.Process(msgBytes, msgBase)
	}
}
Esempio n. 18
0
func ChatroomServer(ws *websocket.Conn) {

	defer ws.Close()

	connid++

	id := connid

	fmt.Printf("connection id: %d\n", id)

	item := conns.PushBack(ws)

	defer conns.Remove(item)

	name := fmt.Sprintf("user%d", id)

	SendMessage(nil, fmt.Sprintf("{\"user_name\":\"%s\"}", name))

	r := bufio.NewReader(ws)

	for {
		data, err := r.ReadBytes('\n')
		if err != nil {
			fmt.Printf("disconnected id : %d\n", id)
			SendMessage(item, fmt.Sprintf("%s offline\n", name))
			break
		}

		fmt.Printf("%s:%s", name, data)

		SendMessage(item, fmt.Sprintf("%s\t>%s", name, data))
	}
}
Esempio n. 19
0
func BuildConnection(ws *websocket.Conn) {
	email := ws.Request().URL.Query().Get("email")

	if email == "" {
		return
	}
	email = template.HTMLEscapeString(email)
	onlineUser := &OnlineUser{
		InRoom:     runningActiveRoom,
		Connection: ws,
		Send:       make(chan Message, 256),
		UserInfo: &User{
			Email:    email,
			Name:     strings.Split(email, "@")[0],
			Gravatar: helper.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()
}
Esempio n. 20
0
func EchoServer(ws *websocket.Conn) {
	var req map[string]string

	defer server.Remove(ws)

	for websocket.JSON.Receive(ws, &req) != io.EOF {
		fmt.Println(ws.Request().RemoteAddr)
		switch req["event"] {
		case "ADD":
			roomName := req["roomName"]
			server.Add(roomName, ws)
			fmt.Println(server.Room)
		case "ECHO":
			for _, client := range server.Room[req["roomName"]] {
				websocket.Message.Send(client, req["message"])
			}
		case "CLOSE":
			fmt.Println(req["message"])
		}
	}

	fmt.Println("connection ", ws)
	fmt.Println(server.Clients)
	fmt.Println(server.Room)
}
Esempio n. 21
0
func handleWebsocket(s *websocket.Conn) {
	var data [8192]uint8
	log.Printf("Opened WebSocket")
	startTime := time.Now()

	f, err := os.OpenFile(fmt.Sprintf("%s/uploads/%s.mp3", *htdocsDir, time.Now().Format(time.RFC3339)), os.O_WRONLY|os.O_CREATE, 0644)
	if err != nil {
		log.Printf("os.OpenFile failed: %v", err)
		return
	}
	defer f.Close()

	sum := 0
	count := 0

	for {
		n, err := s.Read(data[:])
		if err != nil {
			log.Printf("s.Read failed: %v", err)
			break
		}
		log.Printf("Received WebSocket frame: %d bytes", n)
		count++
		sum += n
		if _, err := f.Write(data[:n]); err != nil {
			log.Printf("f.Write failed: %v", err)
		}
	}

	duration := time.Since(startTime)

	log.Printf("Closed WebSocket, received %d frames (%d bytes), took %s (%.3f kb/s)", count, sum, duration, (float64(sum)/duration.Seconds())/float64(1024))
}
func (dws DockerWebSockets) listen(ws *websocket.Conn) {
	//	defer ws.Close()
	defer printDebug(fmt.Sprintf("Closing Websocket to", ws.RemoteAddr()))

	var senderid string
	printDebug(fmt.Sprintf("starting listening to:", ws.RemoteAddr()))
	dec := json.NewDecoder(ws)
	for {
		//		msg, err :=rece?iveMsg(ws)

		var m websocketMsg
		//decoder := util.GetCodec("JSON")
		err := dec.Decode(&m)
		printDebug(m)
		//err = decoder.Decode(msg, &m)
		if err != nil {
			printDebug(err)
			dws.remove(senderid)
			return
		}
		senderid = m.Id

		if m.Type == messages.DOCK {
			conn := NewConnection(ws)
			dws.agent.InitDocking(m.Id, m.Codec, m.Msg, conn)
		} else {
			dws.agent.ProcessMsg(m.Id, m.Type, m.Codec, m.Msg)
		}
	}

}
Esempio n. 23
0
func writer(ws *websocket.Conn, me string, c chan []byte) {

	for {

		if !ws.IsClientConn() {
			break
		}

		b := <-c
		msg := base64.StdEncoding.EncodeToString(b)
		fmt.Printf("Packet received in writer - length %v\n", len(b))
		//fmt.Println(msg)

		var data *T = new(T)
		data.MsgId = time.Now().UnixNano()
		data.Reply = false
		data.To = "collectd"
		data.Msg = msg
		data.From = me
		err := websocket.JSON.Send(ws, data)
		if err != nil {
			log.Fatal(err)
		}

	}

}
Esempio n. 24
0
// Read from socket and write to websocket
func ReadSocket(ws *websocket.Conn, conn *net.TCPConn) {
	reader := bufio.NewReader(conn)
	var line string = ""
	for {
		if reader == nil {
			break
		}
		buffer, isPrefix, err := reader.ReadLine()
		if err != nil {
			break
		}
		// fmt.Println("ReadSocket: got", len(buffer), "bytes")
		line = line + string(buffer)
		if !isPrefix {
			// fmt.Println("Sending message to web socket:", line)
			err = websocket.Message.Send(ws, line)
			if err != nil {
				_ = conn.Close()
			}
			line = ""
		}
	}
	fmt.Println("ReadSocket exit")
	ws.Close()
}
Esempio n. 25
0
func receiver(ws *websocket.Conn, p *player.Player) chan int {
	quit := make(chan int, 0)
	go func() {
		for {
			m := &player.Message{}
			err := websocket.JSON.Receive(ws, m)
			if err != nil {
				break
			}
			if m.Ping != "" {
				fmt.Printf(
					"%s %s %s\n",
					time.Now().UTC(),
					time.Since(p.PingSent),
					ws.Request().RemoteAddr,
				)
			} else {
				p.FromClient <- m
			}
		}
		p.Disconnected = true
		quit <- 1
	}()
	return quit
}
Esempio n. 26
0
func getResolution(ws *websocket.Conn) (width int64, height int64) {
	request := ws.Request()
	dtsize := request.FormValue("dtsize")

	if !strings.Contains(dtsize, "x") {
		width = 800
		height = 600
	} else {
		sizeparts := strings.Split(dtsize, "x")

		width, _ = strconv.ParseInt(sizeparts[0], 10, 32)
		height, _ = strconv.ParseInt(sizeparts[1], 10, 32)

		if width < 400 {
			width = 400
		} else if width > 1920 {
			width = 1920
		}

		if height < 300 {
			height = 300
		} else if height > 1080 {
			height = 1080
		}
	}

	return width, height
}
Esempio n. 27
0
func handleViewer(conn *websocket.Conn) {
	conn.SetReadDeadline(time.Now().Add(10 * time.Second))
	var viewId string
	if err := websocket.Message.Receive(conn, &viewId); err != nil {
		return
	}

	slideId := index.getSlideId(viewId)
	if slideId == "" {
		return
	}

	listener := &slideListener{ch: make(chan int)}
	registry.addListener(slideId, listener)

	for {
		slide := listener.get(1 * time.Minute)
		if slide != 0 {
			conn.SetDeadline(time.Now().Add(10 * time.Second))
			if err := websocket.Message.Send(conn, fmt.Sprintf("%d", slide)); err != nil {
				registry.removeListener(slideId, listener)
				return
			}

			continue
		}

		if err := ping(conn); err != nil {
			registry.removeListener(slideId, listener)
			return
		}
	}
}
Esempio n. 28
0
func initSocket(ws *websocket.Conn) {
	sendq := make(chan []byte, 100)
	recvq := make(chan []byte, 5)

	width, height := getResolution(ws)
	fmt.Printf("User requested size %d x %d\n", width, height)

	settings := &rdpConnectionSettings{
		hostname,
		username,
		password,
		int(width),
		int(height),
	}

	go rdpconnect(sendq, recvq, settings)
	go processSendQ(ws, sendq)

	read := make([]byte, 1024, 1024)
	for {
		_, err := ws.Read(read)
		if err != nil {
			recvq <- []byte("1")
		}
	}
}
Esempio n. 29
0
// wsHandler is a WebSocket server that handles requests from the WebSocket client in the form of:
// 1. { 'cmd': 'register', 'roomid': $ROOM, 'clientid': $CLIENT' },
// which binds the WebSocket client to a client ID and room ID.
// A client should send this message only once right after the connection is open.
// or
// 2. { 'cmd': 'send', 'msg': $MSG }, which sends the message to the other client of the room.
// It should be sent to the server only after 'regiser' has been sent.
// The message may be cached by the server if the other client has not joined.
//
// Unexpected messages will cause the WebSocket connection to be closed.
func (c *Collider) wsHandler(ws *websocket.Conn) {
	var rid, cid string

	registered := false

	var msg wsClientMsg
loop:
	for {
		err := ws.SetReadDeadline(time.Now().Add(time.Duration(wsReadTimeoutSec) * time.Second))
		if err != nil {
			c.wsError("ws.SetReadDeadline error: "+err.Error(), ws)
			break
		}

		err = websocket.JSON.Receive(ws, &msg)
		if err != nil {
			if err.Error() != "EOF" {
				c.wsError("websocket.JSON.Receive error: "+err.Error(), ws)
			}
			break
		}

		switch msg.Cmd {
		case "register":
			if registered {
				c.wsError("Duplicated register request", ws)
				break loop
			}
			if msg.RoomID == "" || msg.ClientID == "" {
				c.wsError("Invalid register request: missing 'clientid' or 'roomid'", ws)
				break loop
			}
			if err = c.roomTable.register(msg.RoomID, msg.ClientID, ws); err != nil {
				c.wsError(err.Error(), ws)
				break loop
			}
			registered, rid, cid = true, msg.RoomID, msg.ClientID
			c.dash.incrWs()

			defer c.roomTable.deregister(rid, cid)
			break
		case "send":
			if !registered {
				c.wsError("Client not registered", ws)
				break loop
			}
			if msg.Msg == "" {
				c.wsError("Invalid send request: missing 'msg'", ws)
				break loop
			}
			c.roomTable.send(rid, cid, msg.Msg)
			break
		default:
			c.wsError("Invalid message: unexpected 'cmd'", ws)
			break
		}
	}
	// This should be unnecessary but just be safe.
	ws.Close()
}
Esempio n. 30
0
func (this *WebsocketController) HandleWCConnection(ws *websocket.Conn) {
	// Uhh, guessing we are already in a go routine..
	log.Print("CONNECT!")

	defer ws.Close()
	// log.Print("CONNECT!")
	// conn.writer = bufio.NewWriter(conn.conn)

	// dec := json.NewDecoder(bufio.NewReader(conn.conn))
	dec := JSON.NewDecoder(bufio.NewReader(ws))
	writer := &WebsocketWriter{conn: ws}
	for {
		req, err := dec.DecodeRequest()

		if err == io.EOF {
			log.Print(err)
			break
		} else if err != nil {
			log.Print(err)
			break
		}

		controller := this.serverConfig.Router.Match(req.Method(), req.Uri())
		go HandleRequest(req, writer, controller, this.serverConfig)
	}
	log.Print("DISCONNECT!")
}