How to use Ping method of ws Package

Best K6 code snippet using ws.Ping

operations.go

Source:operations.go Github

copy

Full Screen

...14 mgo "gopkg.in/mgo.v2"15 "gopkg.in/mgo.v2/bson"16)17// DeleteDriveDoc deletes the file from google drive18func (c *Controller) DeleteDriveDoc(ping *models.Ping) error {19 // if file id is nil, there is nothing to do20 if ping.FileId == "" {21 return nil22 }23 return c.deleteFile(ping.FileId)24}25// EndPrivateMessage stops the collaboration session and deletes the all26// messages from db27func (c *Controller) EndPrivateMessage(ping *models.Ping) error {28 // if channel id is nil, there is nothing to do29 if ping.ChannelId == 0 {30 return nil31 }32 // fetch the channel33 channel := socialapimodels.NewChannel()34 if err := channel.ById(ping.ChannelId); err != nil {35 // if channel is not there, do not do anyting36 if err == bongo.RecordNotFound {37 return nil38 }39 return err40 }41 canOpen, err := channel.CanOpen(ping.AccountId)42 if err != nil {43 return err44 }45 if !canOpen {46 return nil // if the requester can not open the channel do not process47 }48 // delete the channel49 err = channel.Delete()50 if err != nil {51 return err52 }53 ws, err := modelhelper.GetWorkspaceByChannelId(54 strconv.FormatInt(ping.ChannelId, 10),55 )56 if err != nil {57 return filterErr(err)58 }59 return modelhelper.UnsetSocialChannelFromWorkspace(ws.ObjectId)60}61// UnshareVM removes the users from JMachine document62func (c *Controller) UnshareVM(ping *models.Ping, toBeRemovedUsers []bson.ObjectId) error {63 // if channel id is nil, there is nothing to do64 if ping.ChannelId == 0 {65 return nil66 }67 ws, err := modelhelper.GetWorkspaceByChannelId(68 strconv.FormatInt(ping.ChannelId, 10),69 )70 if err != nil {71 return filterErr(err)72 }73 if len(toBeRemovedUsers) == 0 {74 return nil // no one to remove75 }76 return modelhelper.RemoveUsersFromMachineByIds(ws.MachineUID, toBeRemovedUsers)77}78func (c *Controller) findToBeRemovedUsers(ping *models.Ping) ([]bson.ObjectId, error) {79 ws, err := modelhelper.GetWorkspaceByChannelId(80 strconv.FormatInt(ping.ChannelId, 10),81 )82 if err != nil {83 return nil, filterErr(err)84 }85 machine, err := modelhelper.GetMachineByUid(ws.MachineUID)86 if err != nil {87 return nil, filterErr(err)88 }89 ownerMachineUser := machine.Owner()90 if ownerMachineUser == nil {91 c.log.Critical("owner couldnt found %+v", ping)92 return nil, nil // if we cant find the owner, we cant process the users93 }94 ownerAccount, err := modelhelper.GetAccountByUserId(ownerMachineUser.Id)95 if err != nil {96 return nil, filterErr(err)97 }98 // get workspaces of the owner99 ownersWorkspaces, err := modelhelper.GetWorkspaces(ownerAccount.Id)100 if err != nil {101 return nil, filterErr(err)102 }103 users := partitionUsers(ownerAccount, ownersWorkspaces, ws)104 var toBeRemovedUsers []bson.ObjectId105 for accountID, count := range users {106 // if we count the user more than once, that means user is in another107 // workspace too108 if count > 1 {109 continue110 }111 u, err := modelhelper.GetUserByAccountId(accountID)112 if err != nil {113 return nil, err114 }115 toBeRemovedUsers = append(toBeRemovedUsers, u.ObjectId)116 }117 var filteredUsers []bson.ObjectId118 permanentUsers := make(map[string]struct{})119 for _, user := range machine.Users {120 if user.Permanent {121 permanentUsers[user.Id.Hex()] = struct{}{}122 }123 }124 for _, toBeRemovedUser := range toBeRemovedUsers {125 if _, ok := permanentUsers[toBeRemovedUser.Hex()]; !ok {126 filteredUsers = append(filteredUsers, toBeRemovedUser)127 }128 }129 return filteredUsers, nil130}131// filterErr filters unwanted errors, this is useful on which cases we should132// retry the operation.133func filterErr(err error) error {134 if err == mgo.ErrNotFound { // do not retry on mongo not found135 return nil136 }137 return err138}139func partitionUsers(ownerAccount *mongomodels.Account, ownersWorkspaces []*mongomodels.Workspace, ws *mongomodels.Workspace) map[string]int {140 users := make(map[string]int)141 for _, ownerWS := range ownersWorkspaces {142 // if the workspace belongs to other vm, skip143 if ownerWS.MachineUID != ws.MachineUID {144 continue145 }146 channelID, err := strconv.ParseInt(ownerWS.ChannelId, 10, 64)147 if err != nil {148 continue149 }150 channel := socialapimodels.NewChannel()151 channel.Id = channelID152 participants, err := channel.FetchParticipants(&request.Query{})153 if err != nil {154 return nil155 }156 // fetch the channels of the workspaces157 for _, participant := range participants {158 // skip the owner159 if participant.OldId == ownerAccount.Id.Hex() {160 continue161 }162 if _, ok := users[participant.OldId]; !ok {163 users[participant.OldId] = 0164 }165 users[participant.OldId] = users[participant.OldId] + 1166 }167 }168 return users169}170// RemoveUsersFromMachine removes the collaboraters from the host machine171func (c *Controller) RemoveUsersFromMachine(ping *models.Ping, toBeRemovedUsers []bson.ObjectId) error {172 // if channel id is nil, there is nothing to do173 if ping.ChannelId == 0 {174 return nil175 }176 ws, err := modelhelper.GetWorkspaceByChannelId(strconv.FormatInt(ping.ChannelId, 10))177 if err != nil {178 return filterErr(err)179 }180 m, err := modelhelper.GetMachineByUid(ws.MachineUID)181 if err != nil {182 return filterErr(err)183 }184 // Get the klient.185 klientRef, err := klient.ConnectTimeout(c.kite, m.QueryString, time.Second*10)...

Full Screen

Full Screen

websocket.go

Source:websocket.go Github

copy

Full Screen

...49 }()50 // setMaxSize51 ws.SetReadLimit(wsHandler.MaxMessageSize())52 // set handlers53 setPingPongCloseHandlers(ws, wsHandler, hub)54 // --------------------------55 // ---- websocket process ----56 // --------------------------57 // send msg58 go func() {59 pingTicker := zone.NewTicker(pingPeriod)60 defer pingTicker.Stop()61 for {62 if err := wsHandler.Loop(hub); err != nil {63 return64 }65 select {66 // send message67 case msg, ok := <-hub.getChan():68 if !ok {69 return70 }71 if msg.isDone() {72 return73 }74 if err := msg.send(ws, wsHandler); err != nil {75 _ = log.Error(err)76 return77 }78 // send ping79 case <-pingTicker.C:80 ping := Msg{81 msgType: websocket.PingMessage,82 data: &[]byte{},83 err: nil,84 }85 if err := ping.send(ws, wsHandler); err != nil {86 _ = log.Error(err)87 return88 }89 default:90 continue91 }92 }93 }()94 // read msg95 for {96 msg := &Msg{}97 if msg.scan(ws, wsHandler) != nil {98 _ = log.Error(err)99 return100 }101 switch msg.msgType {102 // TextMessage denotes a text data message. The text message payload is103 // interpreted as UTF-8 encoded text data.104 case websocket.TextMessage:105 fallthrough106 // BinaryMessage denotes a binary data message.107 case websocket.BinaryMessage:108 wsHandler.OnMessage(hub, msg)109 // PingMessage denotes a ping control message. The optional message payload110 // is UTF-8 encoded text.111 case websocket.PingMessage: // defined at SetPingHandler112 // send pong113 pong := Msg{114 msgType: websocket.PongMessage,115 data: &[]byte{},116 err: nil,117 }118 if err := pong.send(ws, wsHandler); err != nil {119 _ = log.Error(err)120 return121 }122 // PongMessage denotes a pong control message. The optional message payload123 // is UTF-8 encoded text.124 case websocket.PongMessage: // defined at SetPongHandler125 // check deadline126 if msg.err != nil {127 _ = log.Error(err)128 return129 }130 case websocket.CloseMessage: // defined at SetCloseHandler131 closeMsg := Msg{132 msgType: websocket.CloseMessage,133 data: &[]byte{},134 err: nil,135 }136 if err := closeMsg.send(ws, wsHandler); err != nil {137 _ = log.Error(err)138 return139 }140 return141 default:142 log.Warn("No websocket handler on this msgType", toto.V{"msgType": msg.msgType})143 }144 }145 }146}147func setPingPongCloseHandlers(ws *websocket.Conn, wsHandler Handler, hub Hub) {148 ws.SetCloseHandler(func(code int, text string) error {149 wsHandler.OnClose(hub, code, text)150 return nil151 })152 ws.SetPingHandler(func(appData string) error {153 wsHandler.OnPing(hub, appData)154 return nil155 })156 ws.SetPongHandler(func(appData string) error {157 wsHandler.OnPing(hub, appData)158 return nil159 })160}...

Full Screen

Full Screen

utils.go

Source:utils.go Github

copy

Full Screen

...14 writeWait = 10 * time.Second15 // Maximum message size allowed from peer.16 maxMessageSize = 819217 // Maximum message size allowed from peer.18 maxPingErrors = 319 // Time allowed to read the next pong message from the peer.20 pongWait = 60 * time.Second21 // Send pings to peer with this period. Must be less than pongWait.22 pingPeriod = (pongWait * 9) / 1023 // Time to wait before force close on connection.24 closeGracePeriod = 10 * time.Second25)26func pumpStdin(ws *websocket.Conn, w chan string) {27 defer ws.Close()28 ws.SetReadLimit(maxMessageSize)29 ws.SetReadDeadline(time.Now().Add(pongWait))30 ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })31 for {32 _, message, err := ws.ReadMessage()33 if err != nil {34 break35 }36 message = append(message)37 log.Println("message in", string(message))38 w <- string(message)39 }40}41func pumpStdout(ws *websocket.Conn, r chan string, done chan struct{}) {42 defer func() {43 }()44 for message := range r {45 log.Println("message out", message)46 ws.SetWriteDeadline(time.Now().Add(writeWait))47 // go look in the db for a city48 query, err := models.NewSignpostQuery(message)49 if err != nil {50 ws.WriteJSON(bson.M{"error": err.Error()})51 continue52 }53 signpost, err := models.NewSignpost(query.Center, query.MinNumberOfSigns, query.MaxNumberOfSigns,54 query.MinDistance, query.MaxDistance, query.MinDifficulty, query.MaxDifficulty)55 if err != nil {56 ws.WriteJSON(bson.M{"error": err.Error()})57 continue58 }59 if err := ws.WriteJSON(signpost); err != nil {60 ws.Close()61 break62 }63 }64 close(done)65 ws.SetWriteDeadline(time.Now().Add(writeWait))66 ws.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))67 time.Sleep(closeGracePeriod)68 ws.Close()69}70func ping(ws *websocket.Conn, done chan struct{}) {71 ticker := time.NewTicker(pingPeriod)72 defer ticker.Stop()73 for {74 select {75 case <-ticker.C:76 wsID := ws.RemoteAddr().String()77 if err := ws.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(writeWait)); err != nil {78 _, ok := pingErrors[wsID]79 if ok {80 pingErrors[wsID]++81 } else {82 pingErrors[wsID] = 183 }84 log.Println("ping:", err)85 if pingErrors[wsID] == maxPingErrors {86 log.Println("closing websocket:", wsID)87 close(done)88 }89 } else {90 delete(pingErrors, wsID)91 }92 case <-done:93 return94 }95 }96}...

Full Screen

Full Screen

Ping

Using AI Code Generation

copy

Full Screen

1import (2var upgrader = websocket.Upgrader{}3func serveWs(w http.ResponseWriter, r *http.Request) {4 fmt.Println(r.Host)5 fmt.Println(r.URL)6 ws, err := upgrader.Upgrade(w, r, nil)7 if err != nil {8 fmt.Println(err)9 }10 for {11 err := ws.WriteMessage(websocket.PingMessage, []byte("ping"))12 if err != nil {13 fmt.Println(err)14 }15 time.Sleep(1 * time.Second)16 }17}18func setupRoutes() {19 http.HandleFunc("/", serveWs)20}21func main() {22 fmt.Println("Distributed Chat App v0.01")23 setupRoutes()24 http.ListenAndServe(":8080", nil)25}

Full Screen

Full Screen

Ping

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 http.HandleFunc("/ping", pingHandler)4 log.Fatal(http.ListenAndServe(":8080", nil))5}6func pingHandler(w http.ResponseWriter, r *http.Request) {7 ws, err := upgrader.Upgrade(w, r, nil)8 if err != nil {9 log.Println(err)10 }11 msgType, msg, err := ws.ReadMessage()12 if err != nil {13 log.Println(err)14 }15 fmt.Println(string(msg))16 err = ws.WriteMessage(msgType, msg)17 if err != nil {18 log.Println(err)19 }20}

Full Screen

Full Screen

Ping

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 http.HandleFunc("/", index)4 http.HandleFunc("/ws", ws)5 http.ListenAndServe(":8080", nil)6}7func index(w http.ResponseWriter, r *http.Request) {8 fmt.Println("index")9 http.ServeFile(w, r, "index.html")10}11func ws(w http.ResponseWriter, r *http.Request) {12 fmt.Println("ws")13 conn, err := websocket.Upgrade(w, r, w.Header(), 1024, 1024)14 if err != nil {15 fmt.Println(err)16 }17 defer conn.Close()18 for {19 _, msg, err := conn.ReadMessage()20 if err != nil {21 fmt.Println(err)22 }23 fmt.Println(string(msg))24 err = conn.WriteMessage(websocket.TextMessage, msg)25 if err != nil {26 fmt.Println(err)27 }28 }29}30import (31var upgrader = websocket.Upgrader{32}33func main() {34 http.HandleFunc("/", index)35 http.HandleFunc("/ws", ws)36 http.ListenAndServe(":8080", nil)37}38func index(w http.ResponseWriter, r *http.Request) {39 fmt.Println("index")40 http.ServeFile(w, r, "index.html")41}42func ws(w http.ResponseWriter, r *http.Request) {43 fmt.Println("ws")44 conn, err := upgrader.Upgrade(w, r, w.Header())45 if err != nil {46 fmt.Println(err)47 }48 defer conn.Close()49 for {50 _, msg, err := conn.ReadMessage()51 if err != nil {52 fmt.Println(err)53 }54 fmt.Println(string(msg))55 err = conn.WriteMessage(websocket.TextMessage, msg)56 if err != nil {57 fmt.Println(err)58 }59 }60}61import (62var upgrader = websocket.Upgrader{

Full Screen

Full Screen

Ping

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println("error in connection")5 }6 defer conn.Close()7 err = conn.WriteMessage(websocket.TextMessage, []byte("hello"))8 if err != nil {9 fmt.Println("error in writing to server")10 }11 _, message, err := conn.ReadMessage()12 if err != nil {13 fmt.Println("error in reading from server")14 }15 fmt.Println(string(message))16}

Full Screen

Full Screen

Ping

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 fmt.Println("Error in dialing", err)5 }6 defer c.Close()7 for {8 err := c.WriteMessage(websocket.PingMessage, []byte("ping"))9 if err != nil {10 fmt.Println("Error in writing ping message", err)11 }12 _, msg, err := c.ReadMessage()13 if err != nil {14 fmt.Println("Error in reading message", err)15 }16 fmt.Printf("Received: %s\n", msg)17 time.Sleep(5 * time.Second)18 }19}20import (21func main() {22 if err != nil {23 fmt.Println("Error in dialing", err)24 }25 defer c.Close()26 for {27 err := c.WriteMessage(websocket.PongMessage, []byte("pong"))28 if err != nil {29 fmt.Println("Error in writing ping message", err)30 }31 _, msg, err := c.ReadMessage()32 if err != nil {33 fmt.Println("Error in reading message", err)34 }35 fmt.Printf("Received: %s\n", msg)36 time.Sleep(5 * time.Second)37 }38}

Full Screen

Full Screen

Ping

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 if err != nil {4 panic(err)5 }6 for {7 time.Sleep(5 * time.Second)8 err := ws.WriteMessage(websocket.PingMessage, []byte("ping"))9 if err != nil {10 panic(err)11 }12 fmt.Println("Ping sent")13 }14}

Full Screen

Full Screen

Ping

Using AI Code Generation

copy

Full Screen

1import "fmt"2import "net"3import "bufio"4import "os"5func main() {6 conn, _ := net.Dial("tcp", "

Full Screen

Full Screen

Ping

Using AI Code Generation

copy

Full Screen

1import (2var (3 upgrader = websocket.Upgrader{4 CheckOrigin: func(r *http.Request) bool { return true },5 }6func wsHandler(w http.ResponseWriter, r *http.Request) {7 ws, err := upgrader.Upgrade(w, r, nil)8 if err != nil {9 log.Println(err)10 }11 defer ws.Close()12 err = ws.WriteMessage(1, []byte("Hello Client!"))13 if err != nil {14 log.Println(err)15 }16 messageType, p, err := ws.ReadMessage()17 if err != nil {18 log.Println(err)19 }20 log.Println(messageType, string(p))21 for {22 mt, message, err := ws.ReadMessage()23 if err != nil {24 log.Println(err)25 }26 log.Println("received:", string(message))27 err = ws.WriteMessage(mt, message)28 if err != nil {29 log.Println(err)30 }31 }32}33func main() {34 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {35 fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))36 })37 http.HandleFunc("/ws", wsHandler)38 go func() {39 time.Sleep(1 * time.Second)40 log.Println("Server is running at port 8080")41 }()42 log.Fatal(http.ListenAndServe(":8080", nil))43}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful