예제 #1
0
func (wc 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(ws))
	conn := WebsocketConnection{conn: ws}
	for {
		var req Request
		err := dec.Decode(&req)

		if err == io.EOF {
			log.Print(err)
			break
		} else if err != nil {
			log.Print(err)
			break
		}
		log.Print(req)
		log.Print(req.Uri())
		controller := wc.serverConfig.Router.Match(req.Method(), req.Uri())

		log.Print("GOT CONTROLLER ")
		log.Print(controller)

		go controller.HandleRequest(&req, conn)
	}
	log.Print("DISCONNECT!")
}
예제 #2
0
파일: web.go 프로젝트: zephyyrr/goFrankNet
func wsHandler(ws *wbs.Conn) {
	defer ws.Close()

	log.Println("Websocket connection recieved.")
	log.Println("Handeling user.")
	handleUser(ws)
}
예제 #3
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")
}
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
}
예제 #5
0
파일: irc.go 프로젝트: lyuyun/loggregator
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)
	}
}
예제 #6
0
파일: main.go 프로젝트: 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)
	}
}
예제 #7
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()
}
예제 #8
0
파일: ksdust_m.go 프로젝트: phutidus/ksdust
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)
			}
		}
	}
}
예제 #9
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())
			}
		}
	}
}
예제 #10
0
파일: stabbey.go 프로젝트: Garoth/StAbbey
/* Keep the player's websocket alive and continue reading from it forever */
func PlayerKeepReading(p interfaces.Player, ws *websocket.Conn) {
	for {
		var message string
		playerOrder := struct {
			CommandCode int
			TickNum     int
			Queue       []string
		}{}

		if e := websocket.Message.Receive(ws, &message); e != nil {
			break
		} else {
			log.Println("Received message on websocket:", message)
			err := json.Unmarshal([]byte(message), &playerOrder)
			if err != nil {
				log.Fatalln("Error Decoding Order: ", string(message))
				break
			}

			o := order.NewOrder(playerOrder.CommandCode, playerOrder.TickNum,
				playerOrder.Queue, p, GAME)
			RUNTIME.AddOrder(o)
		}
	}
	log.Printf("Closing socket for %v", p.GetPlayerId())
	ws.Close()
}
예제 #11
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!")
}
예제 #12
0
//wsHandler now used ws.Config as protocol handshake now supported
func wsHandler(ws *websocket.Conn) {
	defer flow.DontPanic()
	defer ws.Close()

	hdr := ws.Request().Header

	// keep track of connected clients for reload broadcasting
	id := hdr.Get("Sec-Websocket-Key")
	wsClients[id] = ws
	defer delete(wsClients, id)

	// the protocol name is used as tag to locate the proper circuit
	//lightbulb: We use the protocol provided by ws, rather than header, as that contains server accepted value
	tag := ws.Config().Protocol[0]

	fmt.Println("WS Protocol Selected:", tag)

	if tag == "" { //no specific protocol, lets opt for 'default' which just echoes (or return with no circuit!)
		tag = "default"
	}

	g := flow.NewCircuit()
	g.AddCircuitry("head", &wsHead{ws: ws})
	g.Add("ws", "WebSocket-"+tag) //the client has negotiated this support
	g.AddCircuitry("tail", &wsTail{ws: ws})
	g.Connect("head.Out", "ws.In", 0)
	g.Connect("ws.Out", "tail.In", 0)
	g.Run()
}
예제 #13
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] = ""
	log.Println("Number of clients connected:", len(ActiveClients))

	// for loop so the websocket stays open otherwise
	// it'll close after one Receieve and Send
	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
		}

		var msg_arr = strings.Split(clientMessage, "|")
		if msg_arr[0] == "login" && len(msg_arr) == 3 {
			name := msg_arr[1]
			pass := msg_arr[2]

			if pass == User[name] {
				ActiveClients[sockCli] = name

				if err = Message.Send(ws, "login|"+name); err != nil {
					log.Println("Could not send message to ", client, err.Error())
				}
			} else {
				log.Println("login faild:", clientMessage)
			}

		} else if msg_arr[0] == "msg" {
			if ActiveClients[sockCli] != "" {
				clientMessage = "msg|" + time.Now().Format("2006-01-02 15:04:05") + " " + ActiveClients[sockCli] + " Said: " + msg_arr[1]
				for cs, na := range ActiveClients {
					if na != "" {
						if err = Message.Send(cs.websocket, clientMessage); err != nil {
							log.Println("Could not send message to ", cs.clientIP, err.Error())
						}
					}
				}
			}
		}
	}
}
예제 #14
0
파일: main.go 프로젝트: silentfl/GoApp
func WebSocketServer(ws *websocket.Conn) {
	log.Printf("ws connect: %v\n", ws.RemoteAddr())
	var msg Message
	var in []byte
	CurrUser := users.Add(ws)
	defer users.Del(ws)
	defer func() { ws.Close(); log.Printf("ws disconnect: %v\n", ws.RemoteAddr()) }()

	for {
		err := websocket.Message.Receive(ws, &in)
		if err != nil { //пользователь ушел
			return
		}
		err = json.Unmarshal(in, &msg) //TO DO: обработка ошибок
		if err != nil {
			log.Println("json err:", err)
			return
		}
		log.Printf("%+v", msg)
		switch msg.Types {
		case "message":
			msg.User = CurrUser.Nickname
			broadcastMessage <- msg
		case "users":
			if msg.Action == "list" { //остальные типы action игнорятся
				go sendUserlist(ws)
			}
		}
	}
}
예제 #15
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
			}
		}
	}
}
예제 #16
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
		}
	}
}
예제 #17
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)
}
예제 #18
0
func wsockHandler(ws *websocket.Conn) {
	// Start a sniffer.
	req := ws.Request()
	req.ParseForm()
	local := req.Form.Get("local")
	remote := req.Form.Get("remote")

	if local != "" && remote != "" {
		l, err := net.Listen("tcp", local)
		if err != nil {
			sendMessage(ws, "error", err.Error())
			ws.Close()
			return
		}

		go func() {
			buf := make([]byte, 256)
			for {
				_, err := ws.Read(buf)
				if err != nil {
					l.Close()
					return
				}
			}
		}()

		fn := func(m map[string]interface{}) error {
			return websocket.JSON.Send(ws, m)
		}
		fromClient := webSniffer{fn, true}
		fromServer := webSniffer{fn, false}
		err = sniffer.SniffToOutput(l, remote, fromClient, fromServer)
		ws.Close()
	}
}
예제 #19
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))
	}
}
예제 #20
0
파일: panpigo.go 프로젝트: biorisk/panpigo
// 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
	}
}
예제 #21
0
파일: websocket.go 프로젝트: stanhu/logslam
func (ws *WebSocketServer) wslogsHandler(w *websocket.Conn) {
	source := w.Request().FormValue("source")
	host := fmt.Sprintf("%s/%d", w.RemoteAddr().String(), time.Now().UnixNano())

	defer func() {
		log.Printf("[%s] closing websocket conn", w.RemoteAddr().String())
		ws.b.DelSubscriber(host)
		w.Close()
	}()

	log.Printf("[%s] accepting websocket conn", w.RemoteAddr().String())

	r := make(chan *buffer.Event, recvBuffer)
	ws.b.AddSubscriber(host, r)

	for {
		select {
		case ev := <-r:
			if len(source) > 0 {
				if ev.Source != source {
					continue
				}
			}

			err := websocket.Message.Send(w, *ev.Text)
			if err != nil {
				log.Printf("[%s] error sending ws message: %v", w.RemoteAddr().String(), err.Error())
				return
			}
		}
	}
}
예제 #22
0
파일: publish.go 프로젝트: jimjh/octopi
// producer handles incoming produce requests. Producers may send multiple
// produce requests on the same persistent connection. The function exits when
// an `io.EOF` is received on the connection.
func producer(conn *websocket.Conn) {

	defer conn.Close()

	for {

		var request protocol.ProduceRequest

		err := websocket.JSON.Receive(conn, &request)
		if err == io.EOF { // graceful shutdown
			break
		}

		if nil != err {
			log.Warn("Ignoring invalid message from %v.", conn.RemoteAddr())
			continue
		}

		ack := new(protocol.Ack)
		if err := broker.Publish(request.Topic, request.ID, &request.Message); nil != err {
			log.Error(err.Error())
			ack.Status = protocol.StatusFailure
		} else {
			ack.Status = protocol.StatusSuccess
		}
		// TODO: should redirect if this node is not the leader

		websocket.JSON.Send(conn, &ack)

	}

	log.Info("Closed producer connection from %v.", conn.RemoteAddr())

}
예제 #23
0
파일: handler.go 프로젝트: jbrukh/goavatar
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)
	}
}
예제 #24
0
// Creates and returns a new Connection object
// Finds token within request URI
func NewConnection(ws *websocket.Conn) (*Connection, error) {

	if origin := ws.RemoteAddr(); origin.String() != "http://lab.quantumtrip.org" && origin.String() != "localhost" {
		log.Println("Unkown origin: \n\tTo: %s\n\tFrom: %s", origin, ws.Request().RemoteAddr)
		//os.Exit(68)
		msg := "Please email [email protected] for access"
		b, err := json.Marshal(msg)
		if err != nil {
			log.Panic(err)
		}

		ws.Write(b)
	}

	query := ws.Request().URL.Query()
	token := GetToken(query)

	user, err := getUser(token)
	if err != nil {
		log.Println(err.Error())
		ws.Close()
		return nil, err
	}

	client := ClientInfo{token, ws.Request().RemoteAddr, user}
	log.Printf("Connection opened %+v", client)

	return &Connection{
		make(chan bool),
		make(chan interface{}),
		client,
		ws,
	}, nil
}
예제 #25
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)

}
예제 #26
0
func handle(conn *websocket.Conn) {
	logger.Printf("new websocket client: %s", conn.RemoteAddr())
	defer conn.Close()
	req := "1s"
	if err := websocket.Message.Receive(conn, &req); err != nil {
		logger.Printf("error request: %s", err)
		return
	}
	if freq, err := time.ParseDuration(req); err != nil {
		logger.Printf("invalid request: %s", req)
		websocket.Message.Send(conn, "invalid request")
		return
	} else {
		logger.Printf("new request for ticks from %s, period=%s", conn.RemoteAddr(), freq)
		T := time.NewTicker(freq)
		defer T.Stop()
		ticks := 0
		for t := range T.C {
			if ticks >= 16 {
				return
			}
			err := websocket.Message.Send(conn, t.String())
			if err != nil {
				logger.Printf("error sending: %s", err)
				return
			}
			ticks++
		}
	}
}
예제 #27
0
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()
}
예제 #28
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)
		}
	}
}
예제 #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()
}
예제 #30
0
파일: gentle.go 프로젝트: samofly/gentle
func (s *server) Serve(ws *websocket.Conn) {
	defer log.Printf("Connection closed.")
	defer ws.Close()

	go downstream(ws, s.m.Sub())

	in := bufio.NewScanner(ws)
	var js jsonSplitter
	in.Split(js.Split)
	for in.Scan() {
		log.Printf("incoming json message: %s", in.Text())
		var req webRequest
		if err := json.Unmarshal(in.Bytes(), &req); err != nil {
			log.Printf("Failed to unmarshal incoming request: %v, err: %v", in.Bytes(), err)
			return
		}
		if req.Raw == "" {
			log.Printf("Only raw messages are currently supported")
			continue
		}
		s.m.Send(req.Raw)
	}
	if err := in.Err(); err != nil {
		log.Printf("Error while reading from connection with %v: %v", ws.RemoteAddr(), err)
	}
}