Best K6 code snippet using ws.Send
main.go
Source:main.go
...75 if "" == kefuList[cln].ip {76 zhaodao = 177 withWho = cln78 kefuList[cln] = kefu{kefuList[cln].name, 1, clnIP}79 websocket.Message.Send(ws, "æ¾å°å为"+kefuList[cln].name+"ç客æ")80 break81 }82 }83 if 1 == zhaodao {84 break85 } else {86 websocket.Message.Send(ws, "ææ¶æ¾ä¸å°å®¢æ")87 time.Sleep(time.Second * 3)88 }89 }90 } else {91 kefuList[ws] = kefu{user, 0, ""}92 }93 if "" != server {94 for "" == kefuList[ws].ip { //çå¾
游客访é®95 for {96 var msg string97 toWs := youke[kefuList[ws].ip]98 err := websocket.Message.Receive(ws, &msg)99 if err != nil {100 delete(kefuList, ws)101 fmt.Println("ä¸ä¸ªå®¢ææ线äº")102 return103 }104 websocket.Message.Send(toWs, kefuList[ws].ip+": "+msg)105 }106 }107 } else {108 for {109 var msg string110 err := websocket.Message.Receive(ws, &msg)111 if err != nil {112 delete(youke, clnIP)113 for aa := range kefuList {114 if clnIP == kefuList[aa].ip {115 kefuList[aa] = kefu{kefuList[aa].name, 1, ""}116 }117 }118 return119 }120 websocket.Message.Send(ws, clnIP+": "+msg)121 websocket.Message.Send(withWho, clnIP+": "+msg)122 _, ok := kefuList[withWho]123 if !ok {124 websocket.Message.Send(ws, "该客ææ线äºï¼æ£å¨ä¸ºä½ éæ°æ¥æ¾")125 goto HERE126 }127 }128 }129}130func helpHandler(w http.ResponseWriter, r *http.Request) {131 userName := r.PostFormValue("username")132 topic := r.PostFormValue("topic")133 contain := r.PostFormValue("contain")134 bodyContain := "user:" + userName + "\r\n" + contain135 user := "zfliu_10@126.com"136 password := "@szlhstlslzf525@"137 host := "smtp.126.com:25"138 to := "zfliu_10@126.com"139 subject := topic140 body := `141 <html>142 <body>143 <h3>144 ` + bodyContain + `145 </h3>146 </body>147 </html>148 `149 fmt.Println("send email")150 hp := strings.Split(host, ":")151 auth := smtp.PlainAuth("", user, password, hp[0])152 var content_type string153 content_type = "Content-Type: text/" + "html" + "; charset=UTF-8"154 msg := []byte("To: " + to + "\r\nFrom: " + user + "<" + user +155 ">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)156 send_to := strings.Split(to, ";")157 err := smtp.SendMail(host, auth, user, send_to, msg)158 if err != nil {159 fmt.Println("Send mail error!")160 fmt.Println(err)161 } else {162 fmt.Println("Send mail success!")163 respon :=164 `<html><h1>åéæåï¼æ们ä¼å°½å¿«å¸®ä½ å¤ç</h1><h1>2ç§åå°è·³è½¬å°ä¸»é¡µé¢</h1>165 <script language=\"javascript\"> 166 function go( ) { 167 window.location="index.html"; 168 } 169 window.setTimeout("go()",1000);//2ç§åæ§è¡å½æ°go 170 </script>171 </html>`172 w.Write([]byte(respon))173 //http.Redirect(w, r, "index.html", http.StatusFound)174 }175}176func sysMgrHandler(w http.ResponseWriter, r *http.Request) {177 cookie, _ := r.Cookie("User")178 userName := cookie.Value179 //fmt.Println(userName)180 db, _ := sql.Open("mysql", "root:root@/chatroom?charset=utf8")181 rows, _ := db.Query("select uid,admin from users where username=?", userName)182 defer db.Close()183 id := 0184 admin := 0185 for rows.Next() {186 rows.Scan(&id, &admin)187 }188 if id > 0 {189 if 1 == admin {190 files, _ := ioutil.ReadFile("./views/sysManage.html")191 sour := []byte("{{%}}")192 replace := []byte(cookie.Value)193 respon := bytes.Replace(files, sour, replace, -1)194 w.Write(respon)195 } else {196 w.Write([]byte("éæ³æä½"))197 }198 } else {199 w.Write([]byte("404"))200 }201}202func quitHandler(w http.ResponseWriter, r *http.Request) {203 respon, _ := ioutil.ReadFile("./views/index.html")204 cookie := http.Cookie{205 Name: "User",206 Path: "/",207 MaxAge: -1,208 }209 http.SetCookie(w, &cookie)210 w.Write(respon)211}212func operUserHandler(w http.ResponseWriter, r *http.Request) {213 cookie, _ := r.Cookie("User")214 what := r.URL.Query()["type"][0]215 //fmt.Println(cookie.Value)216 //fmt.Println(what)217 switch what {218 case "add":219 userName := r.URL.Query()["name"][0]220 passWord := r.URL.Query()["pw"][0]221 //fmt.Println(userName + passWord)222 db, _ := sql.Open("mysql", "root:root@/chatroom?charset=utf8")223 rows, _ := db.Query("select uid from users where username=?", userName)224 id := 0225 for rows.Next() {226 rows.Scan(&id)227 }228 if id > 0 {229 w.Write([]byte("ç¨æ·åå·²åå¨"))230 } else {231 db.Exec("insert into users(username,password) values(?,?)", userName, passWord)232 w.Write([]byte("æ·»å æå"))233 }234 db.Close()235 case "del":236 userName := r.URL.Query()["name"][0]237 //fmt.Println(userName)238 db, _ := sql.Open("mysql", "root:root@/chatroom?charset=utf8")239 if userName == cookie.Value {240 w.Write([]byte("ä¸è½å é¤èªå·±"))241 } else {242 db.Exec("delete from users where username=?", userName)243 db.Close()244 w.Write([]byte("å é¤æå"))245 }246 db.Close()247 case "upd":248 //fmt.Println(r.URL)249 userName := r.URL.Query()["name"][0]250 passWord := r.URL.Query()["password"][0]251 var canlogin string252 canlogin = r.URL.Query()["canlogin"][0]253 //fmt.Println(canlogin)254 db, _ := sql.Open("mysql", "root:root@/chatroom?charset=utf8")255 db.Exec("update users set password=?,canlogin=? where username=?", passWord, canlogin, userName)256 //fmt.Print(userName + passWord)257 db.Close()258 w.Write([]byte("æ´æ°æå"))259 default:260 w.Write([]byte("åçäºä¸äºä¸ºæ¢çé误"))261 }262}263func userManagerPrintHandler(w http.ResponseWriter, r *http.Request) {264 cookie, _ := r.Cookie("User")265 userName := cookie.Value266 //fmt.Println(userName)267 db, _ := sql.Open("mysql", "root:root@/chatroom?charset=utf8")268 rows, _ := db.Query("select uid,admin from users where username=?", userName)269 defer db.Close()270 id := 0271 admin := 0272 for rows.Next() {273 rows.Scan(&id, &admin)274 }275 if id > 0 {276 if 1 == admin {277 files, _ := ioutil.ReadFile("./views/userManage.html")278 sour := []byte("{{%}}")279 replace := []byte(cookie.Value)280 respon := bytes.Replace(files, sour, replace, -1)281 w.Write(respon)282 } else {283 w.Write([]byte("ä½ æ²¡ææé"))284 }285 } else {286 w.Write([]byte("éæ³æä½"))287 }288}289func userLoginHandler(w http.ResponseWriter, r *http.Request) {290 userName := r.PostFormValue("Username")291 passWord := r.PostFormValue("Password")292 db, _ := sql.Open("mysql", "root:root@/chatroom?charset=utf8")293 stmt, _ := db.Prepare(("select uid,canlogin from users where username=? and password=?"))294 rows, _ := stmt.Query(userName, passWord)295 user_id := 0296 var canlogin string297 for rows.Next() {298 rows.Scan(&user_id, &canlogin)299 }300 if user_id > 0 {301 if "1" == canlogin {302 t := time.Now().Format("2006-01-02")303 db.Exec("update users set time=? where uid=?", t, user_id)304 cookie := http.Cookie{305 Name: "User",306 Value: userName,307 Path: "/",308 MaxAge: 86400,309 }310 http.SetCookie(w, &cookie)311 r.AddCookie(&cookie)312 //fmt.Println(cookie)313 http.Redirect(w, r, "/chatRoom", http.StatusFound)314 } else {315 respon := `316 ä½ è¢«ç®¡çåç¦æ¢ç»é317 `318 w.Write([]byte(respon))319 }320 } else {321 page := "ç»é失败"322 w.Write([]byte(page))323 }324 db.Close()325}326func userMgrHandler(w http.ResponseWriter, r *http.Request) {327 cookie, _ := r.Cookie("User")328 userName := cookie.Value329 //fmt.Println(userName)330 db, _ := sql.Open("mysql", "root:root@/chatroom?charset=utf8")331 rows, _ := db.Query("select uid,admin from users where username=?", userName)332 defer db.Close()333 id := 0334 admin := 0335 for rows.Next() {336 rows.Scan(&id, &admin)337 }338 //fmt.Println(id)339 respon := "[" //åéå°å®¢æ·ç«¯çä¸è¥¿340 //var JSONrespon UserInfo341 if id > 0 {342 if 1 == admin {343 rows, _ = db.Query("select username,password,canlogin,time from users")344 for rows.Next() {345 var un, ps, cl, t string346 rows.Scan(&un, &ps, &cl, &t)347 respon += "{"348 respon += "\"name\":\"" + un + "\","349 respon += "\"password\":\"" + ps + "\","350 respon += "\"canlogin\":\"" + cl + "\","351 respon += "\"time\":\"" + t + "\""352 respon += "},"353 }354 respon += "]"355 respon = strings.Replace(respon, ",]", "]", 1)356 //respon := `[{"id":"1","name" : "aaa","password" : "111","canlogin" : "1"},357 // {"id":"2","name" : "bbb","password" : "111","canlogin" : "1"},358 // {"id":"3","name" : "ccc","password" : "111","canlogin" : "1"}]`359 //fmt.Println(respon)360 w.Write([]byte(respon))361 } else {362 w.Write([]byte("éæ³æä½"))363 }364 } else {365 w.Write([]byte("404"))366 }367}368func chatRoomHandler(w http.ResponseWriter, r *http.Request) {369 cookie, err := r.Cookie("User")370 if err == nil {371 //fmt.Println(cookie.Value)372 files, _ := ioutil.ReadFile("./views/chat.html")373 sour := []byte("{{%}}")374 replace := []byte(cookie.Value)375 respon := bytes.Replace(files, sour, replace, -1)376 w.Write(respon)377 } else {378 w.Write([]byte("Worry"))379 }380}381func registerHandler(w http.ResponseWriter, r *http.Request) {382 //fmt.Println(r.Form)383 //fmt.Println(r.URL)384 userName := r.URL.Query()["name"][0]385 passWord := r.URL.Query()["password"][0]386 again := r.URL.Query()["again"][0]387 //fmt.Println(userName + " 111")388 if passWord != again {389 respon := "两次è¾å
¥å¯ç ä¸ä¸è´ï¼è¯·éæ°è¾å
¥"390 w.Write([]byte(respon))391 return392 }393 db, _ := sql.Open("mysql", "root:root@/chatroom?charset=utf8")394 rows, _ := db.Query("select uid from users where username=?", userName)395 id := 0396 for rows.Next() {397 rows.Scan(&id)398 }399 //fmt.Println(id)400 if id > 0 {401 //respBuf, _ := ioutil.ReadFile("./views/register2.html")402 respBuf := "ç¨æ·å·²åå¨"403 w.Write([]byte(respBuf))404 } else {405 db.Exec("insert into users(username,password) values(?,?)", userName, passWord)406 //cookie := http.Cookie{407 // Name: "User",408 // Value: userName,409 // Path: "/",410 // MaxAge: 86400,411 //}412 //http.SetCookie(w, &cookie)413 //http.Redirect(w, r, "/chatRoom", http.StatusFound)414 db.Close()415 respon := "注åæå"416 w.Write([]byte(respon))417 }418}419type info struct {420 ws *websocket.Conn421 ip string422 relogin int423}424var (425 connClns = make(map[string]info)426)427func chatHandler(ws *websocket.Conn) {428 defer ws.Close()429 clnIP := ws.Request().RemoteAddr430 user := ws.Request().URL.Query().Get("user")431 //fmt.Println(clnIP)432 //------------------433 value, exists := connClns[user]434 if exists {435 fmt.Println("ä¸çº¿åipï¼" + value.ip)436 websocket.Message.Send(connClns[user].ws, "ä½ çå¸å·å¨å«çå°æ¹ç»é,ä½ è¢«è¿«ä¸çº¿")437 connClns[user].ws.Close()438 //delete(connClns, user)439 connClns[user] = info{ws, clnIP, 1}440 fmt.Println("顶å·åipï¼" + connClns[user].ip)441 } else {442 connClns[user] = info{ws, clnIP, 0}443 //fmt.Println(clnIP)444 }445 //------------------446 //connClns[user] = info{ws, clnIP}447 db, _ := sql.Open("mysql", "root:root@/chatroom?charset=utf8")448 rows, _ := db.Query("select friend from friends where username=?", user)449 online := "/online"450 offline := "/offline"451 friends := "friendsList"452 var scan string453 var toAll []string454 for rows.Next() {455 rows.Scan(&scan)456 va, ex := connClns[scan]457 if ex {458 online = online + "/" + scan459 fmt.Println(va.ip)460 } else {461 offline = offline + "/" + scan462 }463 //friends = friends + "/" + scan464 toAll = append(toAll, scan)465 }466 friends += online + offline467 //fmt.Println(user + "ç好å" + friends)468 websocket.Message.Send(ws, friends) //对èªå·±å 载好åå表469 fmt.Println(toAll)470 for i := 0; i < len(toAll); i++ { //åè¯å
¶å®äººåºè¯¥å·æ°å¥½åå表471 _, ex := connClns[toAll[i]]472 fmt.Print(toAll[i])473 if ex {474 websocket.Message.Send(connClns[toAll[i]].ws, "shouldRefresh")475 fmt.Println("éç¥" + toAll[i] + "shouldRefresh")476 } else {477 fmt.Println(ex)478 }479 }480 //----------------离线éç¥----------------481 {482 rows, _ = db.Query("select wfrom,wto,msg from offlinemsg where wto=?", user)483 var wfrom string484 var wto string485 var wmsg string486 for rows.Next() {487 rows.Scan(&wfrom, &wto, &wmsg)488 websocket.Message.Send(ws, wfrom+"å¨ä½ 离线æ¶å¯¹ä½ 说ï¼"+wmsg)489 }490 db.Exec("delete from offlinemsg where wto=?", user)491 db.Close()492 }493 //---------------------------------------494 for {495 var sour string496 var hand []string497 err := websocket.Message.Receive(ws, &sour)498 fmt.Println("æ¶å°ï¼" + user + "," + sour)499 if err != nil {500 for i := 0; i < len(toAll); i++ { //åè¯å
¶å®äººåºè¯¥å·æ°å¥½åå表501 _, ex := connClns[toAll[i]]502 if ex {503 websocket.Message.Send(connClns[toAll[i]].ws, "shouldRefresh")504 }505 }506 if 1 == connClns[user].relogin {507 connClns[user] = info{connClns[user].ws, connClns[user].ip, 0}508 } else {509 delete(connClns, user)510 }511 return512 }513 hand = strings.Split(sour, ",")514 fmt.Println(hand)515 switch hand[0] {516 case "shouldRefresh":517 {518 db, _ := sql.Open("mysql", "root:root@/chatroom?charset=utf8")519 rows, _ := db.Query("select friend from friends where username=?", user)520 online := "/online"521 offline := "/offline"522 friends := "friendsList"523 scan = ""524 for rows.Next() {525 rows.Scan(&scan)526 va, ex := connClns[scan]527 if ex {528 online = online + "/" + scan529 fmt.Println(va.ip)530 } else {531 offline = offline + "/" + scan532 }533 //friends = friends + "/" + scan534 }535 friends += online + offline536 fmt.Println(user + "ç好å" + friends)537 db.Close()538 websocket.Message.Send(ws, friends) //对èªå·±å 载好åå表539 }540 //æ·»å 好å541 case "addFriend":542 {543 username := hand[1]544 db, _ := sql.Open("mysql", "root:root@/chatroom?charset=utf8")545 rows, _ := db.Query("select uid from users where username = ?", username)546 user_id := 0547 for rows.Next() {548 rows.Scan(&user_id)549 }550 rows.Close()551 rows, _ = db.Query("select username,friend from friends where username=? and friend=?", user, username)552 haveFriend := ""553 haveName := ""554 for rows.Next() {555 rows.Scan(&haveName, &haveFriend)556 fmt.Println(haveName + " " + haveFriend)557 }558 if user_id > 0 { //è¦æ·»å ç人åå¨559 switch username {560 case user:561 websocket.Message.Send(ws, "addFriendFail/ä¸è½æ·»å èªå·±")562 case haveFriend:563 websocket.Message.Send(ws, "addFriendFail/è¦æ·»å ç好åå·²åå¨")564 default:565 db.Exec("insert into friends(username,friend) value(?,?)", user, username)566 //db.Exec("insert into friends(username,friend) value(?,?)", username, user)567 friends = friends + "/" + username568 toAll = append(toAll, username)569 websocket.Message.Send(ws, friends) //好åå表570 websocket.Message.Send(ws, "æ·»å 好åï¼"+hand[1]+"æå")571 fmt.Println("æ·»å 好åæå")572 websocket.Message.Send(ws, "shouldRefresh")573 //websocket.Message.Send(connClns[username].ws, user+"å°ä½ æ·»å 为好å")574 //websocket.Message.Send(connClns[username].ws, user+"å°ä½ æ·»å 为好å")575 }576 } else {577 websocket.Message.Send(ws, "addFriendFail/è¦æ·»å ç好åä¸åå¨")578 fmt.Println("æ·»å 好å失败")579 }580 db.Close()581 }582 //å é¤å¥½å583 case "delFriend":584 {585 db, _ := sql.Open("mysql", "root:root@/chatroom?charset=utf8")586 for i := 1; i < len(hand); i++ {587 db.Exec("delete from friends where username=? and friend=?", user, hand[i])588 websocket.Message.Send(ws, "æåå é¤:"+hand[i])589 friends = strings.Replace(friends, "/"+hand[i], "", 1)590 //friend2 = strings.Replace(friends, "friendsList", "flref", 1)591 fmt.Println(friends)592 for j := range toAll {593 if hand[i] == toAll[j] {594 toAll = append(toAll[:j], toAll[j+1:]...)595 }596 }597 websocket.Message.Send(ws, friends)598 fmt.Printf("å é¤%sæå", hand[i])599 }600 db.Close()601 }602 default:603 {604 parSendMsg := "ä½ å¯¹"605 for i := 1; i < len(hand); i++ {606 if connClns[hand[i]].ip != "" {607 websocket.Message.Send(connClns[hand[i]].ws, user+"å¯¹ä½ è¯´:"+hand[0])608 } else {609 db, _ := sql.Open("mysql", "root:root@/chatroom?charset=utf8")610 db.Exec("insert into offlinemsg(wfrom,wto,msg) value(?,?,?)", user, hand[i], hand[0])611 //fmt.Println("fffffffff")612 db.Close()613 }614 parSendMsg += hand[i] + ","615 }616 parSendMsg += "说:" + hand[0]617 websocket.Message.Send(ws, parSendMsg)618 }619 }620 }621}...
websocket.go
Source:websocket.go
...251type Codec struct {252 Marshal func(v interface{}) (data []byte, payloadType byte, err error)253 Unmarshal func(data []byte, payloadType byte, v interface{}) (err error)254}255// Send sends v marshaled by cd.Marshal as single frame to ws.256func (cd Codec) Send(ws *Conn, v interface{}) (err error) {257 data, payloadType, err := cd.Marshal(v)258 if err != nil {259 return err260 }261 ws.wio.Lock()262 defer ws.wio.Unlock()263 w, err := ws.frameWriterFactory.NewFrameWriter(payloadType)264 if err != nil {265 return err266 }267 _, err = w.Write(data)268 w.Close()269 return err270}271// Receive receives single frame from ws, unmarshaled by cd.Unmarshal and stores272// in v. The whole frame payload is read to an in-memory buffer; max size of273// payload is defined by ws.MaxPayloadBytes. If frame payload size exceeds274// limit, ErrFrameTooLarge is returned; in this case frame is not read off wire275// completely. The next call to Receive would read and discard leftover data of276// previous oversized frame before processing next frame.277func (cd Codec) Receive(ws *Conn, v interface{}) (err error) {278 ws.rio.Lock()279 defer ws.rio.Unlock()280 if ws.frameReader != nil {281 _, err = io.Copy(ioutil.Discard, ws.frameReader)282 if err != nil {283 return err284 }285 ws.frameReader = nil286 }287again:288 frame, err := ws.frameReaderFactory.NewFrameReader()289 if err != nil {290 return err291 }292 frame, err = ws.frameHandler.HandleFrame(frame)293 if err != nil {294 return err295 }296 if frame == nil {297 goto again298 }299 maxPayloadBytes := ws.MaxPayloadBytes300 if maxPayloadBytes == 0 {301 maxPayloadBytes = DefaultMaxPayloadBytes302 }303 if hf, ok := frame.(*hybiFrameReader); ok && hf.header.Length > int64(maxPayloadBytes) {304 // payload size exceeds limit, no need to call Unmarshal305 //306 // set frameReader to current oversized frame so that307 // the next call to this function can drain leftover308 // data before processing the next frame309 ws.frameReader = frame310 return ErrFrameTooLarge311 }312 payloadType := frame.PayloadType()313 data, err := ioutil.ReadAll(frame)314 if err != nil {315 return err316 }317 return cd.Unmarshal(data, payloadType, v)318}319func marshal(v interface{}) (msg []byte, payloadType byte, err error) {320 switch data := v.(type) {321 case string:322 return []byte(data), TextFrame, nil323 case []byte:324 return data, BinaryFrame, nil325 }326 return nil, UnknownFrame, ErrNotSupported327}328func unmarshal(msg []byte, payloadType byte, v interface{}) (err error) {329 switch data := v.(type) {330 case *string:331 *data = string(msg)332 return nil333 case *[]byte:334 *data = msg335 return nil336 }337 return ErrNotSupported338}339/*340Message is a codec to send/receive text/binary data in a frame on WebSocket connection.341To send/receive text frame, use string type.342To send/receive binary frame, use []byte type.343Trivial usage:344 import "websocket"345 // receive text frame346 var message string347 websocket.Message.Receive(ws, &message)348 // send text frame349 message = "hello"350 websocket.Message.Send(ws, message)351 // receive binary frame352 var data []byte353 websocket.Message.Receive(ws, &data)354 // send binary frame355 data = []byte{0, 1, 2}356 websocket.Message.Send(ws, data)357*/358var Message = Codec{marshal, unmarshal}359func jsonMarshal(v interface{}) (msg []byte, payloadType byte, err error) {360 msg, err = json.Marshal(v)361 return msg, TextFrame, err362}363func jsonUnmarshal(msg []byte, payloadType byte, v interface{}) (err error) {364 return json.Unmarshal(msg, v)365}366/*367JSON is a codec to send/receive JSON data in a frame from a WebSocket connection.368Trivial usage:369 import "websocket"370 type T struct {371 Msg string372 Count int373 }374 // receive JSON type T375 var data T376 websocket.JSON.Receive(ws, &data)377 // send JSON type T378 websocket.JSON.Send(ws, data)379*/380var JSON = Codec{jsonMarshal, jsonUnmarshal}...
client_group.go
Source:client_group.go
...11}12func (r WsClientByAuth) remove(w *WsClient) {13 delete(r, w.UID)14}15func (r WsClientByAuth) Send(payload []byte) {16 for _, w := range r {17 w.write(payload)18 }19}20//WsClientManager : [idAuth]21type WsClientManager map[string]WsClientByAuth22func NewWsClientManager() WsClientManager {23 return WsClientManager(map[string]WsClientByAuth{})24}25func (rb WsClientManager) ForEach(cb func(*WsClient)) {26 for _, byAuth := range rb {27 if byAuth != nil {28 for _, w := range byAuth {29 cb(w)30 }31 }32 }33}34func (rb WsClientManager) ForEachByAuth(id string, cb func(*WsClient)) {35 var byAuth = rb[id]36 if byAuth != nil {37 for _, w := range byAuth {38 cb(w)39 }40 }41}42func (rb WsClientManager) Add(w *WsClient, id string) {43 var r = rb[id]44 if r == nil {45 r = newWsClientByAuth()46 rb[id] = r47 }48 r.add(w)49}50func (rb WsClientManager) Remove(w *WsClient, id string) {51 var r = rb[id]52 if r == nil {53 return54 }55 r.remove(w)56 if r.empty() {57 delete(rb, id)58 }59}60func (rb WsClientManager) SendJson(uri string, v interface{}) {61 var payload = BuildJsonMessage(uri, v)62 //fmt.Println("Send Payload: ", string(payload))63 rb.SendRaw(payload)64}65func (rb WsClientManager) SendRaw(payload []byte) {66 for _, r := range rb {67 r.Send(payload)68 }69}70// SendToGroup send data to the group with auth id71// return the number of clients in the group72func (rb WsClientManager) SendToGroup(authID string, uri string, v interface{}) int {73 var r = rb[authID]74 if r == nil {75 return 076 }77 var payload = BuildJsonMessage(uri, v)78 r.Send(payload)79 return len(r)80}81func (rb WsClientManager) Destroy() {82 rb.ForEach(func(w *WsClient) {83 w.Close()84 })85}...
Send
Using AI Code Generation
1import (2var upgrader = websocket.Upgrader{3}4func main() {5 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {6 serveWs(w, r)7 })8 http.ListenAndServe(":8080", nil)9}10func serveWs(w http.ResponseWriter, r *http.Request) {11 fmt.Println(r.Host)12 conn, err := upgrader.Upgrade(w, r, nil)13 if err != nil {14 log.Println(err)15 }16 for {17 mt, message, err := conn.ReadMessage()18 if err != nil {19 log.Println(err)20 }21 fmt.Printf("recv: %s22 err = conn.WriteMessage(mt, message)23 if err != nil {24 log.Println(err)25 }26 }27}28import (29var upgrader = websocket.Upgrader{30}31func main() {32 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {33 serveWs(w, r)34 })35 http.ListenAndServe(":8080", nil)36}37func serveWs(w http.ResponseWriter, r *http.Request) {38 fmt.Println(r.Host)39 conn, err := upgrader.Upgrade(w, r, nil)40 if err != nil {41 log.Println(err)42 }43 for {44 mt, message, err := conn.ReadMessage()45 if err != nil {46 log.Println(err)47 }48 fmt.Printf("recv: %s49 err = conn.WriteMessage(mt, message)50 if err != nil {51 log.Println(err)52 }53 }54}
Send
Using AI Code Generation
1import (2var upgrader = websocket.Upgrader{3 CheckOrigin: func(r *http.Request) bool { return true },4}5func serveWs(w http.ResponseWriter, r *http.Request) {6 fmt.Println(r.Host)7 conn, err := upgrader.Upgrade(w, r, nil)8 if err != nil {9 log.Println(err)10 }11 for {12 messageType, p, err := conn.ReadMessage()13 if err != nil {14 log.Println(err)15 }16 fmt.Println(string(p))17 if err := conn.WriteMessage(messageType, p); err != nil {18 log.Println(err)19 }20 }21}22func setupRoutes() {23 http.HandleFunc("/ws", serveWs)24}25func main() {26 fmt.Println("Distributed Chat App v0.01")27 setupRoutes()28 http.ListenAndServe(":8080", nil)29}30import (31var upgrader = websocket.Upgrader{32 CheckOrigin: func(r *http.Request) bool { return true },33}34func serveWs(w http.ResponseWriter, r *http.Request) {35 fmt.Println(r.Host)36 conn, err := upgrader.Upgrade(w, r, nil)37 if err != nil {38 log.Println(err)39 }40 for {41 messageType, p, err := conn.ReadMessage()42 if err != nil {43 log.Println(err)44 }45 fmt.Println(string(p))46 if err := conn.WriteMessage(messageType, p); err != nil {47 log.Println(err)48 }49 }50}51func setupRoutes() {52 http.HandleFunc("/ws", serveWs)53}54func main() {55 fmt.Println("Distributed Chat App v0.01")56 setupRoutes()57 http.ListenAndServe(":8080", nil)58}
Send
Using AI Code Generation
1import (2func main() {3 u := url.URL{Scheme: "ws", Host: "localhost:8080", Path: "/"}4 fmt.Println("connecting to ", u.String())5 c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)6 if err != nil {7 log.Fatal("dial:", err)8 }9 defer c.Close()10 c.WriteMessage(websocket.TextMessage, []byte("hello"))11}12import (13func main() {14 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {15 u := url.URL{Scheme: "ws", Host: r.Host, Path: "/"}16 fmt.Println("connecting to ", u.String())17 c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)18 if err != nil {19 log.Fatal("dial:", err)20 }21 defer c.Close()22 _, message, err := c.ReadMessage()23 if err != nil {24 log.Println("read:", err)25 }26 fmt.Printf("recv: %s27 })28 log.Fatal(http.ListenAndServe(":8080", nil))29}30import (31func main() {32 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {33 conn, err := upgrader.Upgrade(w, r, nil)34 if err != nil {35 log.Println(err)36 }37 defer conn.Close()38 for {39 mt, message, err := conn.ReadMessage()40 if err != nil {41 log.Println(err)42 }43 fmt.Printf("recv: %s
Send
Using AI Code Generation
1import (2var upgrader = websocket.Upgrader{3 CheckOrigin: func(r *http.Request) bool { return true },4}5func main() {6 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {7 conn, err := upgrader.Upgrade(w, r, nil)8 if err != nil {9 http.NotFound(w, r)10 }11 for {12 messageType, p, err := conn.ReadMessage()13 if err != nil {14 }15 if err = conn.WriteMessage(messageType, p); err != nil {16 }17 }18 })19 http.ListenAndServe(":8080", nil)20}21import (22var upgrader = websocket.Upgrader{23 CheckOrigin: func(r *http.Request) bool { return true },24}25func main() {26 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {27 conn, err := upgrader.Upgrade(w, r, nil)28 if err != nil {29 http.NotFound(w, r)30 }31 for {32 messageType, p, err := conn.ReadMessage()33 if err != nil {34 }35 if err = conn.WriteMessage(messageType, p); err != nil {36 }37 }38 })39 http.ListenAndServe(":8080", nil)40}41import (42var upgrader = websocket.Upgrader{43 CheckOrigin: func(r *http.Request) bool { return true },44}45func main() {46 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {47 conn, err := upgrader.Upgrade(w,
Send
Using AI Code Generation
1import "fmt"2func main() {3 fmt.Println("Hello, 世界")4}5import "fmt"6func main() {7 fmt.Println("Hello, 世界")8}9import "fmt"10func main() {11 fmt.Println("Hello, 世界")12}13import "fmt"14func main() {15 fmt.Println("Hello, 世界")16}17import "fmt"18func main() {19 fmt.Println("Hello, 世界")20}21import "fmt"22func main() {23 fmt.Println("Hello, 世界")24}25import "fmt"26func main() {27 fmt.Println("Hello, 世界")28}29import "fmt"30func main() {31 fmt.Println("Hello, 世界")32}33import "fmt"34func main() {35 fmt.Println("Hello, 世界")36}37import "fmt"38func main() {39 fmt.Println("Hello, 世界")40}41import "fmt"42func main() {43 fmt.Println("Hello, 世界")44}45import "fmt"46func main() {47 fmt.Println("Hello, 世界")48}49import "fmt"50func main() {51 fmt.Println("Hello,
Send
Using AI Code Generation
1import (2var upgrader = websocket.Upgrader{}3func main() {4 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {5 conn, err := upgrader.Upgrade(w, r, nil)6 if err != nil {7 log.Fatal(err)8 }9 })10 http.HandleFunc("/send", func(w http.ResponseWriter, r *http.Request) {11 if ws != nil {12 ws.WriteMessage(1, []byte("Hello from server"))13 }14 })15 http.ListenAndServe(":8080", nil)16}17import (18var upgrader = websocket.Upgrader{}19func main() {20 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {21 conn, err := upgrader.Upgrade(w, r, nil)22 if err != nil {23 log.Fatal(err)24 }25 for {26 messageType, message, err := conn.ReadMessage()27 if err != nil {28 log.Fatal(err)29 }30 fmt.Println(messageType, string(message))31 }32 })33 http.ListenAndServe(":8080", nil)34}35import (36var upgrader = websocket.Upgrader{}37func main() {38 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {39 conn, err := upgrader.Upgrade(w, r, nil)40 if err != nil {41 log.Fatal(err)42 }43 for {44 var message map[string]interface{}45 err := conn.ReadJSON(&message)46 if err != nil {47 log.Fatal(err)48 }49 fmt.Println(message)50 }51 })52 http.ListenAndServe(":8080", nil)53}54import (
Send
Using AI Code Generation
1import (2var (3 upgrader = websocket.Upgrader{4 }5func main() {6 http.HandleFunc("/ws", wsHandler)7 http.ListenAndServe(":8080", nil)8}9func wsHandler(w http.ResponseWriter, r *http.Request) {10 conn, err := upgrader.Upgrade(w, r, nil)11 if err != nil {12 fmt.Println("Failed to set websocket upgrade: %+v", err)13 }14 for {15 err := conn.WriteMessage(websocket.TextMessage, []byte("Hello Client!"))16 if err != nil {17 fmt.Println(err)18 }19 time.Sleep(1 * time.Second)20 }21}22import (23var (24 upgrader = websocket.Upgrader{25 }26func main() {27 http.HandleFunc("/ws", wsHandler)28 http.ListenAndServe(":8080", nil)29}30func wsHandler(w http.ResponseWriter, r *http.Request) {31 conn, err := upgrader.Upgrade(w, r, nil)32 if err != nil {33 fmt.Println("Failed to set websocket upgrade: %+v", err)34 }35 for {36 _, p, err := conn.ReadMessage()37 if err != nil {38 fmt.Println(err)39 }40 fmt.Println(string(p))41 }42}43import (44var (45 upgrader = websocket.Upgrader{46 }47func main() {48 http.HandleFunc("/ws", wsHandler)49 http.ListenAndServe(":8080", nil)50}
Send
Using AI Code Generation
1import (2func main() {3 http.HandleFunc("/", handler)4 log.Fatal(http.ListenAndServe(":8080", nil))5}6func handler(w http.ResponseWriter, r *http.Request) {7 ws, err = websocket.Upgrade(w, r, nil, 1024, 1024)8 if _, ok := err.(websocket.HandshakeError); ok {9 http.Error(w, "Not a websocket handshake", 400)10 } else if err != nil {11 log.Println(err)12 }13 write()14}15func write() {16 for {17 time.Sleep(1 * time.Second)18 err := ws.WriteMessage(websocket.TextMessage, []byte("Hello Client!"))19 if err != nil {20 log.Println(err)21 }22 }23}24func read() {25 for {26 _, msg, err := ws.ReadMessage()27 if err != nil {28 log.Println(err)29 }30 fmt.Println(string(msg))31 }32}33import (34func main() {35 http.HandleFunc("/", handler)36 log.Fatal(http.ListenAndServe(":8080", nil))37}38func handler(w http.ResponseWriter, r *http.Request) {39 ws, err = websocket.Upgrade(w, r, nil, 1024, 1024)40 if _, ok := err.(websocket.HandshakeError); ok {41 http.Error(w, "Not a websocket handshake", 400)42 } else if err != nil {43 log.Println(err)44 }45 go read()46}47func write() {48 for {49 time.Sleep(1 * time.Second)50 err := ws.WriteMessage(websocket.TextMessage, []byte("Hello Client!"))51 if err != nil {52 log.Println(err)53 }54 }55}56func read() {57 for {58 _, msg, err := ws.ReadMessage()59 if err != nil {60 log.Println(err)61 }
Send
Using AI Code Generation
1import (2var upgrader = websocket.Upgrader{3}4func main() {5 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {6 fmt.Fprintf(w, "Hello World")7 })8 http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {9 conn, err := upgrader.Upgrade(w, r, nil)10 if err != nil {11 log.Println(err)12 }13 for {14 mt, message, err := conn.ReadMessage()15 if err != nil {16 log.Println(err)17 }18 fmt.Printf("recv: %s", message)19 err = conn.WriteMessage(mt, message)20 if err != nil {21 log.Println(err)22 }23 }24 })25 log.Fatal(http.ListenAndServe(":8080", nil))26}27import (28func main() {29 http.Handle("/", websocket.Handler(func(ws *websocket.Conn) {30 for {31 if err = websocket.Message.Receive(ws, &reply); err != nil {32 fmt.Println("Can't receive")33 }34 fmt.Println("Received back from client: " + reply)35 fmt.Println("Sending to client: " + msg)36 if err = websocket.Message.Send(ws, msg); err != nil {37 fmt.Println("Can't send")38 }39 }40 }))41 if err := http.ListenAndServe(":12345", nil); err != nil {42 log.Fatal("ListenAndServe:", err)43 }44}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!