//Handle websocket connection
//
//The t parameters contain the section to which the handle is associated with Controls<=>Server Video / Controls<=>Client Videos
func (l *Link) handleWS(o *Link, t rocproto.Packet_Section) {

	defer l.ws.Close()
	defer func() { l.ws = nil }()

	quit := make(chan bool)

	go func() {

		defer func() { quit <- true }()

		for {
			m := new(rocproto.Packet)
			_, buff, err := l.ws.ReadMessage()
			if misc.CheckError(err, "Receiving data from conn", false) != nil {
				return
			}
			if err = checkBuffer(-1, buff, m); err != nil {
				e := NewError(rocproto.Error_Packet, err.Error(), int32(t&^rocproto.Packet_CONTROL_SERVER))
				log.Println("Error : ", e)
				l.out <- e
				continue
			}
			log.Println("Received ==>	", m)
			log.Println(m.Header & uint32(t))
			routPacket(m, l, o, t)
		}
	}()
	for {
		select {
		case <-quit:
			return
		case m := <-l.out:
			log.Printf("Sending ==>	%v\n", m)
			b, err := proto.Marshal(m)
			if misc.CheckError(err, "linker.go/handleWS", false) != nil {
				if m == nil {
					return
				}
				continue
			}
			err = l.ws.WriteMessage(websocket.BinaryMessage, b)
			if misc.CheckError(err, "linker.go/handleWS", false) != nil {
				return
			}
		}
	}
}
//TODO Insert buffer len and check
//Handle TCP connection
//
//The t parameters contain the section to which the handle is associated with Controls<=>Server Video / Controls<=>Client Videos
func (l *Link) handleConn(o *Link, t rocproto.Packet_Section) {

	buff := make([]byte, 128)
	quit := make(chan bool)
	go func() {

		defer func() { quit <- true }()

		m := new(rocproto.Packet)
		for {
			i, err := l.conn.Read(buff[0:])
			if misc.CheckError(err, "Receiving data from conn", false) != nil {
				return
			}
			if err = checkBuffer(i, buff, m); err != nil {
				e := NewError(rocproto.Error_Packet, err.Error(), int32(t&^rocproto.Packet_CONTROL_SERVER))
				log.Println("Error : ", e)
				l.out <- e
				continue
			}
			log.Println("Received ==>	", m)
			routPacket(m, l, o, t)
		}
	}()
	for {
		select {
		case <-quit:
			return
		case m := <-l.out:
			b, err := proto.Marshal(m)
			if misc.CheckError(err, "linker.go/handleConn", false) != nil {
				continue
			}
			_, err = l.conn.Write(b)
			if misc.CheckError(err, "linker.go/handleConn", false) != nil {
				return
			}
		}
	}
}