func (g *game) Start(ws *websocket.Conn) { defer ws.Close() var player user.User for { if err := websocket.JSON.Receive(ws, &player); err != nil { panic(err) return } player.Socket = ws g.Players[player.Name] = player for k, v := range g.Players { if k == player.Name { continue } if err := websocket.JSON.Send(v.Socket, player); err != nil { delete(g.Players, k) go g.SendMessageAll(&Message{ Method: "destroy", UserName: k, }) } } } }
func handleStatusWS(conn *websocket.Conn) { // log.Printf("Web client connected.\n") timer := time.NewTicker(1 * time.Second) for { // The below is not used, but should be if something needs to be streamed from the web client ever in the future. /* var msg SettingMessage err := websocket.JSON.Receive(conn, &msg) if err == io.EOF { break } else if err != nil { log.Printf("handleStatusWS: %s\n", err.Error()) } else { // Use 'msg'. } */ // Send status. <-timer.C update, _ := json.Marshal(&globalStatus) _, err := conn.Write(update) if err != nil { // log.Printf("Web client disconnected.\n") break } } }
func ProcessRunAttached(ws *websocket.Conn) *httperr.Error { vars := mux.Vars(ws.Request()) header := ws.Request().Header app := vars["app"] process := vars["process"] command := header.Get("Command") release := header.Get("Release") height, _ := strconv.Atoi(header.Get("Height")) width, _ := strconv.Atoi(header.Get("Width")) _, err := models.Provider().ProcessRun(app, process, structs.ProcessRunOptions{ Command: command, Height: height, Width: width, Release: release, Stream: ws, }) if provider.ErrorNotFound(err) { return httperr.New(404, err) } if err != nil { return httperr.Server(err) } return nil }
func AppLogs(ws *websocket.Conn) *httperr.Error { app := mux.Vars(ws.Request())["app"] header := ws.Request().Header var err error follow := true if header.Get("Follow") == "false" { follow = false } since := 2 * time.Minute if s := header.Get("Since"); s != "" { since, err = time.ParseDuration(s) if err != nil { return httperr.Errorf(403, "Invalid duration %s", s) } } err = models.Provider().LogStream(app, ws, structs.LogStreamOptions{ Filter: header.Get("Filter"), Follow: follow, Since: time.Now().Add(-1 * since), }) if err != nil { if strings.HasSuffix(err.Error(), "write: broken pipe") { return nil } return httperr.Server(err) } return nil }
func socketHandler(ws *websocket.Conn) { fmt.Println("In socketHandler" + ws.Request().RequestURI) var msg DbgMessage err := websocket.JSON.Receive(ws, &msg) if err != nil { fmt.Println("socketHandler: got error", err) _ = websocket.Message.Send(ws, "FAIL:"+err.Error()) return } if msg.Command != "start" { fmt.Println("socketHandler: terminating, 'start' expected.") _ = websocket.Message.Send(ws, "FAIL: 'start' expected)") return } var startMsg StartMessage err = json.Unmarshal(msg.Payload, &startMsg) if err != nil { fmt.Println("socketHandler: wrong payload", err) _ = websocket.Message.Send(ws, "FAIL:"+err.Error()) return } fmt.Println("socketHandler: received start message, exec = " + startMsg.Exec) // Create communication channels. fromProcess := make(chan string) toProcess := make(chan string) fromSocket := make(chan DbgMessage) toSocket := make(chan string) // Start processing the messages. go process(fromProcess, toProcess, fromSocket, toSocket) // Start the child process go processHandler(fromProcess, toProcess) // Launch a goroutine for sending messages through the websocket. // TODO(jarin) Handle termination properly. go func() { for { select { case tosend := (<-toSocket): err := websocket.Message.Send(ws, tosend) if err != nil { fmt.Println("socketHandler sender error", err) return } } } }() // Process incoming messages from the socket and pass them to the channel. for { err := websocket.JSON.Receive(ws, &msg) if err != nil { fmt.Println("socketHandler receive error", err) return } fromSocket <- msg } }
func echoHandler(ws *websocket.Conn) { var err error var message Message client := ClientConn{ws, ws.Request().RemoteAddr} log.Println("Client connected:", client.ip) for { // получили сообщенько if err = websocket.JSON.Receive(ws, &message); err != nil { log.Println("Disconnected waiting", err.Error()) return } // разбираем, назначаем мастером того, кто так представился if message.Data == "master" { master = &client log.Println("Master client:", master.ip) continue } // если не мастера, то некому слать if master == nil { continue } // шлем то, что пришло, мастеру if err = websocket.JSON.Send(master.ws, message); err != nil { log.Println("Could not send message to ", master.ip, err.Error()) } } }
// 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() }
// SystemLogs returns the logs for the Rack func SystemLogs(ws *websocket.Conn) *httperr.Error { header := ws.Request().Header var err error follow := true if header.Get("Follow") == "false" { follow = false } since := 2 * time.Minute if s := header.Get("Since"); s != "" { since, err = time.ParseDuration(s) if err != nil { return httperr.Errorf(403, "Invalid duration %s", s) } } err = models.Provider().SystemLogs(ws, structs.LogStreamOptions{ Filter: header.Get("Filter"), Follow: follow, Since: time.Now().Add(-1 * since), }) if err != nil { return httperr.Server(err) } return nil }
func (c *Client) Stream(path string, headers map[string]string, in io.Reader, out io.WriteCloser) error { origin := fmt.Sprintf("https://%s", c.Host) endpoint := fmt.Sprintf("wss://%s%s", c.Host, path) config, err := websocket.NewConfig(endpoint, origin) if err != nil { return err } config.TlsConfig = &tls.Config{ InsecureSkipVerify: true, } config.Header.Set("Version", c.Version) userpass := fmt.Sprintf("convox:%s", c.Password) userpass_encoded := base64.StdEncoding.EncodeToString([]byte(userpass)) config.Header.Add("Authorization", fmt.Sprintf("Basic %s", userpass_encoded)) for k, v := range headers { config.Header.Add(k, v) } config.TlsConfig = &tls.Config{ InsecureSkipVerify: true, } var ws *websocket.Conn if proxy := os.Getenv("HTTPS_PROXY"); proxy != "" { ws, err = c.proxyWebsocket(config, proxy) } else { ws, err = websocket.DialConfig(config) } if err != nil { return err } defer ws.Close() var wg sync.WaitGroup if in != nil { go io.Copy(ws, in) } if out != nil { wg.Add(1) go copyAsync(out, ws, &wg) } wg.Wait() out.Close() return nil }
func scoreboardHandler(ws *websocket.Conn) { defer ws.Close() fmt.Fprint(ws, currentResult) sendedResult := currentResult lastUpdate := time.Now() for { if sendedResult != currentResult || time.Now().After(lastUpdate.Add(time.Minute)) { sendedResult = currentResult lastUpdate = time.Now() _, err := fmt.Fprint(ws, currentResult) if err != nil { log.Println("Socket closed:", err) return } } time.Sleep(time.Second) } }
func (this *socketManager) wsOnConnect(ws *websocket.Conn) { var err error var p payload defer func() { if err = ws.Close(); err != nil { logger.Info.Println("Websocket could not be closed", err.Error()) } }() //Client connected to websocket connection := connection{ws} //Keep a reference to the connection this.connections[&connection] = true logger.Info.Println("WebSocket Connection event ...") logger.Info.Println("Number of clients connected ...", len(this.connections)) //Get the last messages from the zmqDealer TCP pipe this.getLastMessages(connection) //Wait a bit for the last messages to send... time.Sleep(3 * time.Second) // Loop to keep websocket open for { if err = websocket.JSON.Receive(ws, &p); err != nil { //Socket is closed if logger.Info.Println("Websocket Disconnected...", err.Error()) //Remove connection from active connections delete(this.connections, &connection) logger.Info.Println("Number of clients connected ...", len(this.connections)) return } } }
func (self *Server) webSocketHandler(conn *websocket.Conn) { dispatcher := NewDispatcher(self) for { data := map[string]interface{}{} err := websocket.JSON.Receive(conn, &data) if err != nil { if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() { fmt.Println(err) continue } if err == io.EOF { fmt.Println(fmt.Sprintf("Client Dissconected :%s", conn.RemoteAddr())) break } else { fmt.Println(fmt.Sprintf("Receive Data Failed %s", err)) break } } fmt.Println("Dispatch", data) err = dispatcher.Dispatch(conn, data) if err != nil { fmt.Println(fmt.Sprintf("Dispatch Failed %s", err)) } } defer func() { conn.Close() }() }
func BuildConnection(ws *websocket.Conn) { email := ws.Request().URL.Query().Get("email") if email == "" { return } onlineUser := &OnlineUser{ InRoom: runningActiveRoom, Connection: ws, Send: make(chan Message, 256), UserInfo: &User{ Email: email, Name: strings.Split(email, "@")[0], Gravatar: libs.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() }
func split(data []byte, atEOF bool, conn *websocket.Conn, callback ReadCallBack) (adv int, token []byte, err error) { l := len(data) if l < 6 { return 0, nil, nil } if l > 100000 { conn.Close() log.Println("invalid query!") return 0, nil, errors.New("to large data!") } var len1, len2 int len1 = int(binary.LittleEndian.Uint16(data[:2])) len2 = int(binary.LittleEndian.Uint32(data[2:6])) offset := 0 if len1+len2+6 > l { conn.Close() log.Println("invalid data", len1, len2, l) return 0, nil, errors.New("invalid data") } offset += len1 + len2 + 6 head := string(data[6 : 6+len1]) tail := data[6+len1 : 6+len1+len2] callback(conn, head, tail) return offset, []byte{}, nil }
func BuildConnection(ws *websocket.Conn) { log.Info("BuildConnection()") token := ws.Request().URL.Query().Get("token") log.Debug(token) var uci userConnectionInfo err := validateToken(token, time.Now(), ws.RemoteAddr(), &uci) if err != nil { log.WithFields(log.Fields{ "error": err, }).Error("validation error") // how should this reply to the client? return } onlineUser := &OnlineUser{ Connection: ws, Uci: uci, Send: make(chan envelope, 256), } runningRoom.Users[onlineUser] = true go onlineUser.PushToClient() onlineUser.PullFromClient() delete(runningRoom.Users, onlineUser) log.Info("tore down user connection") }
// handle implements a WebSocket handler. func (r *Reader) handle(ws *websocket.Conn) { // Close the connection when the client requests it, or when we finish streaming, whichever happens first closeConnOnce := &sync.Once{} closeConn := func() { closeConnOnce.Do(func() { ws.Close() }) } negotiated := ws.Config().Protocol r.selectedProtocol = negotiated[0] defer close(r.err) defer closeConn() go func() { defer runtime.HandleCrash() // This blocks until the connection is closed. // Client should not send anything. IgnoreReceives(ws, r.timeout) // Once the client closes, we should also close closeConn() }() r.err <- messageCopy(ws, r.r, !r.protocols[r.selectedProtocol].Binary, r.ping, r.timeout) }
func testServerMetrics(ws *websocket.Conn) { var b []byte b = make([]byte, 1000) length, _ := ws.Read(b) var m metricsPayload _ = json.Unmarshal(b[:length], &m) test := mtests[currentTest] if m.User != test.expMetrics.User { globalT.Fatalf("Unexpected user") } for _, v := range m.Metrics.Tasks { appFound := false for _, vv := range test.expMetrics.Metrics.Tasks { if vv.App == v.App { appFound = true if v.PendingCount != vv.PendingCount || v.RunningCount != vv.RunningCount { log.Debugf("%#v", test.expMetrics.Metrics.Tasks) log.Debugf("%#v", m.Metrics.Tasks) globalT.Fatalf("Unexpected values") } } } if !appFound { globalT.Fatalf("Received unexpected metric for %s", v.App) } } }
/** * Event -> On connection opened */ func (server *server) onConnectionOpened(conn *websocket.Conn) { defer server.Close(conn) log.Printf("Connection opened: %v", conn.Request().RemoteAddr) client := NewClient(conn, server) server.startClient(client) }
func (self *Handler) PushSocketHandler(ws *websocket.Conn) { requestID := ws.Request().Header.Get(HeaderID) sock := PushWS{Uaid: "", Socket: ws, Store: self.store, Logger: self.logger, Born: time.Now()} if self.logger.ShouldLog(INFO) { self.logger.Info("handler", "websocket connection", LogFields{"rid": requestID}) } defer func() { now := time.Now() // Clean-up the resources self.app.Server().HandleCommand(PushCommand{DIE, nil}, &sock) self.metrics.Timer("socket.lifespan", now.Sub(sock.Born)) self.metrics.Increment("socket.disconnect") }() self.metrics.Increment("socket.connect") NewWorker(self.app, requestID).Run(&sock) if self.logger.ShouldLog(INFO) { self.logger.Info("main", "Server for client shut-down", LogFields{"rid": requestID}) } }
/** * Close connection */ func (server *server) Close(ws *websocket.Conn) { err := ws.Close() if err != nil { server.Error(err) } }
func (conn *Conn) initialize(ws *websocket.Conn) { negotiated := ws.Config().Protocol conn.selectedProtocol = negotiated[0] p := conn.protocols[conn.selectedProtocol] if p.Binary { conn.codec = rawCodec } else { conn.codec = base64Codec } conn.ws = ws conn.channels = make([]*websocketChannel, len(p.Channels)) for i, t := range p.Channels { switch t { case ReadChannel: conn.channels[i] = newWebsocketChannel(conn, byte(i), true, false) case WriteChannel: conn.channels[i] = newWebsocketChannel(conn, byte(i), false, true) case ReadWriteChannel: conn.channels[i] = newWebsocketChannel(conn, byte(i), true, true) case IgnoreChannel: conn.channels[i] = newWebsocketChannel(conn, byte(i), false, false) } } close(conn.ready) }
func (c *Client) Connect(s *websocket.Conn) { c.knownEnts = make(map[uint32]struct{}) c.c = s c.pinger = time.NewTicker(time.Second) c.latency = 5 c.ponged = true encoder := json.NewEncoder(s) c.encoder = encoder c.origin = s.Request().RemoteAddr log.Println("+", c.origin) ent := NewEntity() ent.x = 20 ent.y = 20 ent.z = 20 ent.owner = c c.owns = ent clientLock.Lock() client[c] = c clientLock.Unlock() c.Send("WORLD", level) go c.Pings() c.ReadForever() }
func addLogs(ws *websocket.Conn) { var err error defer func() { msg := &errMsg{} if err != nil { msg.Error = err.Error() log.Errorf("failure in logs webservice: %s", err) } websocket.JSON.Send(ws, msg) ws.Close() }() req := ws.Request() t := context.GetAuthToken(req) if t == nil { err = errors.Errorf("wslogs: no token") return } if t.GetAppName() != app.InternalAppName { err = errors.Errorf("wslogs: invalid token app name: %q", t.GetAppName()) return } err = scanLogs(ws) if err != nil { return } }
func (s *Server) Accept(ws *websocket.Conn) { ws.PayloadType = websocket.BinaryFrame if _, err := NewConnection(s, ws); err != nil { ws.SetDeadline(time.Now().Add(2 * time.Millisecond)) ws.Close() } }
func handleTrafficWS(conn *websocket.Conn) { trafficMutex.Lock() for _, traf := range traffic { if !traf.Position_valid { // Don't send unless a valid position exists. continue } trafficJSON, _ := json.Marshal(&traf) conn.Write(trafficJSON) } trafficMutex.Unlock() // Subscribe the socket to receive updates. trafficUpdate.AddSocket(conn) // Connection closes when function returns. Since uibroadcast is writing and we don't need to read anything (for now), just keep it busy. for { buf := make([]byte, 1024) _, err := conn.Read(buf) if err != nil { break } if buf[0] != 0 { // Dummy. continue } time.Sleep(1 * time.Second) } }
func (c WebSockApp) AxisMovementWidgetWebSocket(user string, ws *websocket.Conn) revel.Result { revel.INFO.Printf("%s", "WS_AXIS_MOV request recieved") defer ws.Close() newmessages := make(chan string) //quit := make(chan struct{}) go func() { var msg string err := websocket.Message.Receive(ws, &msg) if err != nil { close(newmessages) return } newmessages <- msg }() for { select { case msg := <-newmessages: //TODO:Change printf on cmds to virtual keyboard if strings.HasPrefix(msg, "X") { revel.INFO.Printf("%s", "X_AXIS cmd recieved") } if strings.HasPrefix(msg, "Y") { revel.INFO.Printf("%s", "Y_AXIS cmd recieved") } if strings.HasPrefix(msg, "Z") { revel.INFO.Printf("%s", "Z_AXIS cmd recieved") } } } }
// Main handler upon client web connection to the server func handler(sock *websocket.Conn) { fmt.Println("- - - - - - - - - - - - - - - - - -") fmt.Println("Client has connected to the server!") // Read the initial message upon client connection var msg = make([]byte, 512) _, err := sock.Read(msg) if err != nil { log.Println(err) return } for { // Receive the sftp auth information and store in a map n, err := sock.Read(msg) if err != nil { log.Println(err) return } fmt.Println("Received data from the client: ", string(msg[:n])) json := parse(msg[:n]) go handle[json.Function](json.ConnId, json.Data, sock) } }
func ircHandler(ws *websocket.Conn) { var err error var clientmessage string current := ClientConn{ws, ws.Request().RemoteAddr} clients[current] = 0 fmt.Println("number of clients connected ", len(clients)) for { if err = message.Receive(ws, &clientmessage); err != nil { delete(clients, current) fmt.Println("client disconnect,", len(clients), " clients remain") return } clientmessage = "<" + hash(current.ip) + "> " + clientmessage for cs, _ := range clients { if err = message.Send(cs.websocket, clientmessage); err != nil { fmt.Println("sending failed") } } } }
// HandleWS implements a websocket handler. func (w *WatchServer) HandleWS(ws *websocket.Conn) { defer ws.Close() done := make(chan struct{}) go func() { var unused interface{} // Expect this to block until the connection is closed. Client should not // send anything. websocket.JSON.Receive(ws, &unused) close(done) }() for { select { case <-done: w.watching.Stop() return case event, ok := <-w.watching.ResultChan(): if !ok { // End of results. return } w.fixup(event.Object) obj, err := watchjson.Object(w.codec, &event) if err != nil { // Client disconnect. w.watching.Stop() return } if err := websocket.JSON.Send(ws, obj); err != nil { // Client disconnect. w.watching.Stop() return } } } }
func handleStatistic(ws *websocket.Conn) { for k, v := range ws.Config().Header { log.Debug.Println(k, " - ", v) } ws.Write([]byte("Hi")) }