func WebsocketHandler(ws *websocket.Conn) { key := ws.Request().Header.Get("Sec-Websocket-Key") client := Client{ws, key} Srv.register(client) defer func() { Srv.unregister(client) }() for { msg := make([]byte, 512) n, err := ws.Read(msg) if err != nil { break } var cmd Command json.Unmarshal(msg[:n], &cmd) log.Println(cmd.Event) client.process(cmd) } }
func protocol(conn *websocket.Conn) (*Request, error) { // read content length buf := make([]byte, 8) n, err := conn.Read(buf) if err != nil { return nil, err } if n != 8 { return nil, ErrPackageHeaderLength } length, err := strconv.ParseInt(string(buf), 10, 32) if err != nil { return nil, ErrPackageHeaderLength } // limit to 50M if length < 1 || length > 50*1024*1024 { return nil, ErrContentLength } // read all content by length buffer := new(bytes.Buffer) i, err := io.CopyN(buffer, conn, length) if i != length { return nil, ErrPackageHeaderLength } // parse request return ParseRequest(buffer.Bytes()) }
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 socketHandler(ws *websocket.Conn) { for { receivedStream := make([]byte, 256) byteCount, err := ws.Read(receivedStream) if err != nil { return } if byteCount > 0 { inputHeaders := make(map[string]string) decode_err := json.Unmarshal(receivedStream[:byteCount], &inputHeaders) if decode_err != nil { return } out := runPlugins("secred_key", "endpoint_XXX", "consumer_XXX") jsonOut, encode_err := json.Marshal(out.Headers) if encode_err != nil { return } ws.Write(jsonOut) } } }
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) } } }
func StartReading(conn *websocket.Conn) (<-chan []byte, <-chan bool) { log.Print("start reading...") var msg []byte sendChan := make(chan []byte) breakChan := make(chan bool) go func() { for { var tmp = make([]byte, 512) n, err := conn.Read(tmp) if err == io.EOF { breakChan <- true break } if err != nil { log.Fatal(err) } if msg != nil { msg = append(msg, tmp[:n]...) } else { msg = tmp[:n] } if n != 512 { sendChan <- msg msg = nil } } }() return sendChan, breakChan }
func websocketUploadServer(ws *websocket.Conn) { dlId := ws.Request().URL.Path[len("/api/upload_ws/"):] bf := GetBounceFile(dlId) if bf == nil { ws.Write([]byte("ERROR! Download with this ID does not exist.")) return } var dataBuffer [50000]byte // 50 KB arbitrary total := 0 for { numBytes, err := ws.Read(dataBuffer[:]) total += numBytes dataCopy := append([]byte{}, dataBuffer[:numBytes]...) bf.SendData(dataCopy) if err == io.EOF { break } if err != nil { // Oops! ws.Write([]byte("ERROR! " + err.Error())) break } ws.Write([]byte("OK")) } }
// 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 readConn(t *testing.T, ws *websocket.Conn) { buf := make([]byte, 4096) n, err := ws.Read(buf) if err != nil { t.Error(err) } t.Log(string(buf[:n])) }
func read(t *testing.T, conn *websocket.Conn) string { var data = make([]byte, 512) n, err := conn.Read(data) if err != nil { t.Errorf("conn.Read(%v) got error: %v, want nil", data, err) } return string(data[0:n]) }
func EchoServer(ws *websocket.Conn) { cm.register <- ws for { buf := make([]byte, 256) ws.Read(buf) cm.broadcast <- buf } }
func readKey(ws *websocket.Conn) string { var key = make([]byte, KEY_LENGTH+4) // KEY_LENGTH + 4 because what we receive is ["..key."] _, err := ws.Read(key) if err != nil { //log.Println(err) return "" } return cleanKey(key) }
// WSRead reads from a websocket and print the read messages to STDOUT. func WSRead(ws *websocket.Conn) { msg := make([]byte, 512) for { n, err := ws.Read(msg) if err != nil { log.Fatal(err) } fmt.Printf("<< %s\n", msg[:n]) } }
func WebsocketHandler(ws *websocket.Conn) { id := eventManager.On("*@websocket", func(topic string, payload interface{}) { ws.Write([]byte(topic)) }) data := make([]byte, 1) ws.Read(data) // received bytes or connection died: close it. eventManager.Off(id) ws.Close() }
func webHandler(conn *websocket.Conn) { data := make([]byte, 120) n, err := conn.Read(data) checkerr(err) fmt.Printf("msg<------[%s]\n", string(data[:n])) m, err := conn.Write(data[:n]) checkerr(err) fmt.Printf("msg------->[%s]\n", string(data[:m])) defer conn.Close() }
// main START OMIT func echoHandler(ws *websocket.Conn) { log.Print("data is recived.") //io.Copy(ws, ws) buf := make([]byte, 100) for { ws.Read(buf) log.Print(string(buf)) ws.Write(buf) } }
func echoServer(ws *websocket.Conn) { request := make([]byte, 10000) n, err := ws.Read(request) if err != nil { fmt.Println("Error", err.Error()) return } rStr := string(request[:n]) fmt.Println("Read:", n, "It was ", rStr, " type:", ws.Request().FormValue("l")) ws.Write([]byte(rStr)) }
// handles reading messages from the web socket and passing them through the // given chan. If an error occurs, the websocket.CloseFrame signal is sent // through the chan. func readDaemon(ws *websocket.Conn, msgCh chan []byte) { for { msg := make([]byte, 1024) n, err := ws.Read(msg) if err != nil { msgCh <- []byte{websocket.CloseFrame} return } msgCh <- msg[:n] } }
func waitio(conn *websocket.Conn, mych chan string) { buffer := make([]byte, 1024) for { n, err := conn.Read(buffer) if err != nil { close(mych) return } mych <- string(buffer[:n]) } }
// Sends "true" to the done channel when either // the websocket is closed or after a timeout func signalWsClose(ws *websocket.Conn, done chan bool) { buf := make([]byte, 0) expires := time.Now().Add(RequestTimeout) for { _, err := ws.Read(buf) expired := time.Now().After(expires) if err == io.EOF || expired { done <- true return } } }
// Helper function to send an WS request to a given path. urlStr is assumed to // be the url from a httptest.Server func SendWSRequest(urlStr, data string, t *testing.T) (string, error) { if data == "" { return "", fmt.Errorf("cannot send no data to a websocket") } u, err := url.Parse(urlStr) if err != nil { return "", err } u.Scheme = "ws" origin := "http://localhost/" errc := make(chan error) wsc := make(chan *websocket.Conn) go func() { ws, err := websocket.Dial(u.String(), "", origin) if err != nil { errc <- err return } wsc <- ws }() var ws *websocket.Conn select { case err := <-errc: return "", err case ws = <-wsc: case <-time.After(time.Second * 2): return "", fmt.Errorf("websocket dial timed out") } defer ws.Close() msgc := make(chan string) go func() { if _, err := ws.Write([]byte(data)); err != nil { errc <- err return } var msg = make([]byte, 512) var n int if n, err = ws.Read(msg); err != nil { errc <- err return } msgc <- string(msg[:n]) }() select { case err := <-errc: return "", err case msg := <-msgc: t.Logf("response from ws: '%s'", msg) return msg, nil case <-time.After(time.Second * 2): return "", fmt.Errorf("websocket request timed out") } }
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 } } }
func echoHandler(ws *websocket.Conn) { msg := make([]byte, 512) n, err := ws.Read(msg) if err != nil { log.Fatal(err) } fmt.Printf("Receive: %s\n", msg[:n]) m, err := ws.Write(msg[:n]) if err != nil { log.Fatal(err) } fmt.Printf("Send: %s\n", msg[:m]) }
// Helper function to read a complete message from a WebSocket (because the API makes it hard) func readWebSocketMessage(conn *websocket.Conn) ([]byte, error) { var message []byte buf := make([]byte, 100) for { n, err := conn.Read(buf) if err != nil { return nil, err } message = append(message, buf[0:n]...) if n < len(buf) { break } } return message, nil }
func handleWeatherWS(conn *websocket.Conn) { // Subscribe the socket to receive updates. weatherUpdate.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 inLoop(ws *websocket.Conn, errors chan<- error, in chan<- []byte) { var msg = make([]byte, 512) for { var n int var err error n, err = ws.Read(msg) if err != nil { errors <- err continue } in <- msg[:n] } }
func (prod *Websocket) handleConnection(conn *websocket.Conn) { idx := atomic.AddUint32(&prod.clientIdx, 1) >> 31 prod.clients[idx].conns = append(prod.clients[idx].conns, conn) prod.clients[idx].doneCount++ buffer := make([]byte, 8) conn.SetDeadline(time.Time{}) // Keep alive until connection is closed for { if _, err := conn.Read(buffer); err != nil { conn.Close() break } } }
// HandlerChat is called in a goroutine for every connection the websocket accepts. func HandlerChat(conn *websocket.Conn) { defer log.Printf("Closing websocket connection") log.Printf("New websocket connection") // reuse buffers; keep memory usage low! // TODO: Look into reusing memory buffers buff := make([]byte, 1024) var event Event me := new(User) me.conn = conn me.Remote = conn.RemoteAddr().String() loop: for { n, err := conn.Read(buff) if err != nil { if err == io.EOF || err == io.ErrUnexpectedEOF { log.Printf("[chat] EOF\n") conn.Close() break loop } GlobalServer.Errors <- err } log.Printf("Got: '%v'", string(buff[:n])) if err := json.Unmarshal(buff[:n], &event); err != nil { GlobalServer.Errors <- err } switch event.Type { case EVENT_NEWTOPIC: me.HandleNewTopic(event) case EVENT_MESSAGE: me.HandleMessage(event) case EVENT_LEAVE: me.HandleLeave(event) case EVENT_LOGIN: me.HandleLogin(event) case EVENT_VOTE: me.HandleVote(event) default: log.Printf("Unhanlded event type in user handler") } } }
func wsHandler(ws *websocket.Conn) { // //p := unsafe.Pointer(&ws) // //index := ((int)(uintptr(p))) % n // index := rand.Intn(10) // lock := locks[index] // lock.Lock() // wsList[index].PushBack(ws) // lock.Unlock() // // for { // var reply string // if err := websocket.Message.Receive(ws, &reply); err != nil { // fmt.Println("Can't receive because of " + err.Error()) // break // } // fmt.Println(reply) // } for { msg := make([]byte, 12) n, err := ws.Read(msg) if err != nil { fmt.Println("Can't read because of " + err.Error()) } fmt.Printf("Receive: %s\n", msg[:n]) send_msg := "[" + string(msg[:n]) + "]" _, err = ws.Write([]byte(send_msg)) if err != nil { fmt.Println("Can't write because of " + err.Error()) } fmt.Printf("Send: %s\n", send_msg) } // // lock.Lock() // for e := wsList[index].Front(); e != nil; e = e.Next() { // if e.Value.(*websocket.Conn) == ws { // wsList[index].Remove(e) // break // } // } // lock.Unlock() fmt.Println("123") }
func (a *Api) processReceive(conn *websocket.Conn, execId string, rwc io.WriteCloser) { for { var data = make([]byte, 1024) size, err := conn.Read(data) if err != nil { log.Print(err.Error()) return } if len(data) == 0 { log.Print("An error has occured") return } log.Printf("read:%s\n", data[:size]) switch data[0] { case Input: if !a.PermitWrite { break } _, err := rwc.Write(data[1:size]) if err != nil { return } case Ping: _, err := conn.Write([]byte{Pong}) if err != nil { log.Print(err.Error()) return } case ResizeTerminal: var args argResizeTerminal err = json.Unmarshal(data[1:size], &args) if err != nil { log.Print("Malformed remote command %s %s", err, data[:size]) return } if err := a.client.ExecResize(execId, int(args.Columns), int(args.Rows)); err != nil { log.Errorf("error resizing exec tty:url:%s %s %s", a.client.URL, err, execId) } default: log.Print("Unknown message type") return } } }