Best Selenoid code snippet using main.session
tcpsession_c.go
Source:tcpsession_c.go
...32 // person offline flag33 off chan *ClientTcpSession34 //message pack35 pack IMessagePack36 // session id37 SessionID uint6438 //Dest point39 SvrType define.ERouteId40 //src point41 RegPoint define.ERouteId42 //person StrIdentify43 StrIdentify string44 //45 Name string46}47func NewClientSession(addr string,48 conn *net.TCPConn,49 ctx context.Context,50 SvrType define.ERouteId,51 off chan *ClientTcpSession,52 pack IMessagePack,53 procName string) *ClientTcpSession {54 return &ClientTcpSession{55 RemoteAddr: addr,56 conn: conn,57 send: make(chan []byte, maxMessageSize),58 isAlive: false,59 ctx: ctx,60 pack: pack,61 off: off,62 SvrType: SvrType,63 Name: procName,64 }65}66func (this *ClientTcpSession) Alive() bool {67 return this.isAlive68}69func (this *ClientTcpSession) close(sw *sync.WaitGroup) {70 if this == nil {71 return72 }73 Log.FmtPrintf("session close, svr: %v, regpoint: %v, cache size: %v.", this.SvrType, this.RegPoint, len(this.send))74 GClient2ServerSession.RemoveSession(this.RemoteAddr)75 this.off <- this76 //close(this.send)77 this.conn.CloseRead()78 this.conn.CloseWrite()79 this.conn.Close()80}81func (this *ClientTcpSession) SetSendCache(data []byte) {82 this.send <- data83}84func (this *ClientTcpSession) heartbeatloop(sw *sync.WaitGroup) {85 defer func() {86 sw.Done()87 this.close(sw)88 }()89 ticker := time.NewTicker(time.Duration(cstKeepLiveHeartBeatSec) * time.Second)90 defer ticker.Stop()91 for {92 select {93 case <-this.ctx.Done():94 return95 case <-ticker.C:96 if this.RegPoint == 0 || len(this.StrIdentify) == 0 {97 continue98 }99 sendHeartBeat(this)100 }101 }102}103func (this *ClientTcpSession) sendloop(sw *sync.WaitGroup) {104 defer func() {105 sw.Done()106 this.close(sw)107 }()108 for {109 select {110 case <-this.ctx.Done():111 return112 case data := <-this.send:113 if !this.WriteMessage(data) {114 return115 }116 }117 }118}119func (this *ClientTcpSession) recvloop(sw *sync.WaitGroup) {120 defer func() {121 sw.Done()122 this.close(sw)123 }()124 for {125 select {126 case <-this.ctx.Done():127 return128 default:129 if !this.readMessage() {130 return131 }132 }133 }134}135func (this *ClientTcpSession) WriteMessage(data []byte) (succ bool) {136 if !this.isAlive || len(data) == 0 {137 return138 }139 defer stacktrace.Catchcrash()140 this.conn.SetWriteDeadline(aktime.Now().Add(writeWait))141 //send...142 //Log.FmtPrintln("[client] begin send response message to server, message length: ", len(data))143 _, err := this.conn.Write(data)144 if err != nil {145 Log.FmtPrintln("send data fail, err: ", err)146 return false147 }148 return true149}150func (this *ClientTcpSession) readMessage() (succ bool) {151 defer func() {152 this.Unlock()153 stacktrace.Catchcrash()154 }()155 this.Lock()156 //this.conn.SetReadDeadline(aktime.Now().Add(pongWait))157 if len(this.StrIdentify) == 0 &&158 (this.SvrType == define.ERouteId_ER_ESG || this.SvrType == define.ERouteId_ER_ISG) {159 succ = UnPackExternalMsg(this.conn, this.pack)160 if !succ {161 return162 }163 this.pack.SetRemoteAddr(this.RemoteAddr)164 } else {165 succ = UnPackInnerMsg(this.conn, this.pack)166 if !succ {167 return168 }169 this.StrIdentify = this.pack.GetIdentify()170 }171 var route define.ERouteId172 mainID, _ := this.pack.GetMessageID()173 if (mainID == uint16(MSG_MainModule.MAINMSG_SERVER) ||174 mainID == uint16(MSG_MainModule.MAINMSG_LOGIN)) && len(this.StrIdentify) == 0 {175 this.StrIdentify = this.RemoteAddr176 }177 if len(this.pack.GetIdentify()) == 0 {178 this.pack.SetIdentify(this.StrIdentify)179 }180 if mainID == uint16(MSG_MainModule.MAINMSG_LOGIN) {181 route = define.ERouteId_ER_Login182 } else if mainID >= uint16(MSG_MainModule.MAINMSG_PLAYER) {183 route = define.ERouteId_ER_Game184 }185 if mainID != uint16(MSG_MainModule.MAINMSG_SERVER) &&186 mainID != uint16(MSG_MainModule.MAINMSG_HEARTBEAT) &&187 (this.SvrType == define.ERouteId_ER_ISG) {188 //Log.FmtPrintf("[client] StrIdentify: %v.", this.StrIdentify)189 succ = innerMsgRouteAct(ESessionType_Client, route, mainID, this.pack.GetSrcMsg())190 } else {191 succ = this.checkmsgProc(route) //è·¯ç±æ¶æ¯åè°å¤ç192 }193 return194}195func (this *ClientTcpSession) checkRegisterRet(route define.ERouteId) (exist bool) {196 mainID, subID := this.pack.GetMessageID()197 if mainID == uint16(MSG_MainModule.MAINMSG_SERVER) &&198 uint16(MSG_Server.SUBMSG_SC_ServerRegister) == subID {199 this.StrIdentify = this.RemoteAddr200 if this.SvrType == define.ERouteId_ER_ISG {201 this.Push(define.ERouteId_ER_ESG)202 } else {203 this.Push(define.ERouteId_ER_ISG)204 }205 exist = true206 }207 return208}209func (this *ClientTcpSession) checkHeartBeatRet() (exist bool) {210 mainID, subID := this.pack.GetMessageID()211 if mainID == uint16(MSG_MainModule.MAINMSG_HEARTBEAT) &&212 uint16(MSG_HeartBeat.SUBMSG_SC_HeartBeat) == subID {213 exist = true214 }215 return216}217func (this *ClientTcpSession) checkmsgProc(route define.ERouteId) (succ bool) {218 //Log.FmtPrintf("recv response, route: %v.", route)219 bRegister := this.checkRegisterRet(route)220 bHeartBeat := checkHeartBeatRet(this.pack)221 if bRegister || bHeartBeat {222 succ = true223 return224 }225 succ = msgCallBack(this)226 return227}228func (this *ClientTcpSession) GetPack() (obj IMessagePack) {229 return this.pack230}231func (this *ClientTcpSession) HandleSession(sw *sync.WaitGroup) {232 this.isAlive = true233 atomic.AddUint64(&this.SessionID, 1)234 sw.Add(3)235 go this.recvloop(sw)236 go this.sendloop(sw)237 go this.heartbeatloop(sw)238 this.Name = fmt.Sprintf("client_%v", this.Name)239}240func (this *ClientTcpSession) Push(RegPoint define.ERouteId) {241 //Log.FmtPrintf("[client] push new sesson, reg point: %v.", RegPoint)242 this.RegPoint = RegPoint243 GServer2ServerSession.AddSession(this.RemoteAddr, this)244}245func (this *ClientTcpSession) SetIdentify(StrIdentify string) {246 session := GServer2ServerSession.GetSessionByIdentify(this.StrIdentify)247 if session != nil {248 GServer2ServerSession.RemoveSession(this.StrIdentify)249 this.StrIdentify = StrIdentify250 GServer2ServerSession.AddSession(StrIdentify, session)251 }252}253func (this *ClientTcpSession) Offline() {254}255func (this *ClientTcpSession) SendSvrClientMsg(mainid, subid uint16, msg proto.Message) (succ bool, err error) {256 if !this.isAlive {257 err = fmt.Errorf("[client] send msg session disconnection, mainid: %v, subid: %v.", mainid, subid)258 Log.FmtPrintln("send msg err: ", err)259 return succ, err260 }261 data, err := this.pack.PackClientMsg(mainid, subid, msg)262 if err != nil {263 return succ, err264 }265 this.SetSendCache(data)266 return true, nil267}268func (this *ClientTcpSession) SendInnerSvrMsg(mainid, subid uint16, msg proto.Message) (succ bool, err error) {269 if !this.isAlive {270 err = fmt.Errorf("[client] send svr session disconnection, mainid: %v, subid: %v.", mainid, subid)271 Log.FmtPrintln("send msg err: ", err)272 return false, err273 }274 data, err := this.pack.PackInnerMsg(mainid, subid, msg)275 if err != nil {276 return succ, err277 }278 this.SetSendCache(data)279 return true, nil280}281func (this *ClientTcpSession) SendInnerClientMsg(mainid, subid uint16, msg proto.Message) (succ bool, err error) {282 if !this.isAlive {283 err = fmt.Errorf("[client] session disconnection, mainid: %v, subid: %v.", mainid, subid)284 Log.FmtPrintln("send msg err: ", err)285 return false, err286 }287 if len(this.GetIdentify()) > 0 {288 this.pack.SetIdentify(this.GetIdentify())289 }290 this.pack.SetPostType(MsgPostType_Single)291 data, err := this.pack.PackInnerMsg(mainid, subid, msg)292 if err != nil {293 return succ, err294 }295 this.SetSendCache(data)296 return true, nil297}298func (this *ClientTcpSession) SendInnerBroadcastMsg(mainid, subid uint16, msg proto.Message) (succ bool, err error) {299 if !this.isAlive {300 err = fmt.Errorf("[client] session disconnection, mainid: %v, subid: %v.", mainid, subid)301 Log.FmtPrintln("send msg err: ", err)302 return false, err303 }304 if len(this.GetIdentify()) > 0 {305 this.pack.SetIdentify(this.GetIdentify())306 }307 this.pack.SetPostType(MsgPostType_Broadcast)308 data, err := this.pack.PackInnerMsg(mainid, subid, msg)309 if err != nil {310 return succ, err311 }312 this.SetSendCache(data)313 return true, nil314}...
mgo.go
Source:mgo.go
...13 "github.com/globalsign/mgo/bson"14)15type TAokoMgo struct {16 sync.Mutex17 session *mgo.Session18 UserName string19 Passwd string20 ServiceHost string21 chSessions chan *mgo.Session22 PoolCnt int23 server string24}25func NewMgoConn(server, Username, Passwd, Host string) *TAokoMgo {26 aokomogo := &TAokoMgo{}27 aokomogo.UserName = Username28 aokomogo.Passwd = Passwd29 aokomogo.ServiceHost = Host30 aokomogo.server = server31 //template set 1000 session.32 aokomogo.PoolCnt = int(ado.EMgo_Thread_Cnt)33 aokomogo.chSessions = make(chan *mgo.Session, aokomogo.PoolCnt)34 aokomogo.NewDial()35 return aokomogo36}37func (this *TAokoMgo) NewDial() {38 session, err := this.NewMgoSession()39 if err != nil {40 Log.FmtPrintln(err)41 return42 }43 this.session = session44 for i := 1; i <= this.PoolCnt; i++ {45 this.chSessions <- session.Copy()46 }47 return48}49func (this *TAokoMgo) NewMgoSession() (session *mgo.Session, err error) {50 MdialInfo := &mgo.DialInfo{51 Addrs: []string{this.ServiceHost},52 Username: this.UserName,53 Password: this.Passwd,54 Direct: false,55 Timeout: time.Second * 10,56 PoolLimit: 4096,57 //ReadTimeout: time.Second * 5,58 //WriteTimeout: time.Second * 10,59 }60 session, err = mgo.DialWithInfo(MdialInfo)61 if err != nil {62 err = Log.RetError("mgo dial err: %v.\n", err)63 Log.Error("mgo dial err: %v.\n", err)64 return65 }66 err = session.Ping()67 if err != nil {68 err = Log.RetError("session ping out, err: %v.", err)69 Log.Error("session ping out, err: %v.", err)70 return71 }72 session.SetMode(mgo.Monotonic, true)73 session.SetCursorTimeout(0)74 // focus on those selects.75 //http://www.mongoing.com/archives/172376 Safe := &mgo.Safe{77 J: true, //true:åå
¥è½å°ç£çæä¼è¿å|false:ä¸çå¾
è½å°ç£ç|æ¤é¡¹ä¿è¯è½å°ç£ç78 W: 1, //0:ä¸ä¼getLastError|1:主èç¹æååå
¥å°å
å|æ¤é¡¹ä¿è¯æ£ç¡®åå
¥79 WMode: "majority", //"majority":å¤èç¹åå
¥|æ¤é¡¹ä¿è¯ä¸è´æ§|å¦ææ们æ¯åèç¹ä¸éè¦è¿åªæ¤é¡¹80 }81 session.SetSafe(Safe)82 //session.SetSocketTimeout(time.Duration(5 * time.Second()))83 err = nil84 return85}86func (this *TAokoMgo) Exit() {87 if this.chSessions != nil {88 close(this.chSessions)89 }90}91func (this *TAokoMgo) GetMgoSession() (sess *mgo.Session, err error) {92 this.Lock()93 defer this.Unlock()94 if this.session == nil {95 err = fmt.Errorf("aoko mongo session not get invalid.")96 return97 }98 sess = this.session99 err = nil100 return101}102func (this *TAokoMgo) getMgoSessionByChan() (sess *mgo.Session, err error) {103 this.Lock()104 defer this.Unlock()105 select {106 case s, _ := <-this.chSessions:107 return s, nil108 case <-time.After(time.Duration(1) * time.Second):109 default:110 }111 return nil, fmt.Errorf("aoko mongo session time out and not get.")112}113func MakeMgoModel(Identify, MainModel, SubModel string) string {114 return MainModel + "." + SubModel + "." + Identify115}116func (this *TAokoMgo) QueryAcc(usrName string, OutParam IDBCache) (err error, exist bool) {117 condition := bson.M{OutParam.SubModel() + "." + "username": usrName}118 return this.QueryByCondition(condition, OutParam)119}120func (this *TAokoMgo) QueryOne(Identify string, OutParam IDBCache) (err error, exist bool) {121 condition := bson.M{"_id": Identify}122 return this.QueryByCondition(condition, OutParam)123}124func (this *TAokoMgo) QueryByCondition(condition bson.M, OutParam IDBCache) (err error, exist bool) {125 session, err := this.GetMgoSession()126 if err != nil {127 err = Log.RetError("get sesson err: %v.", err)128 return129 }130 s := session.Clone()131 defer s.Close()132 collection := s.DB(this.server).C(OutParam.MainModel())133 retQuerys := collection.Find(condition)134 count, ret := retQuerys.Count()135 if ret != nil || count == 0 {136 err = Log.RetError("[mgo] query data err: %v, %v.", ret, count)137 return138 }139 selectRet := retQuerys.Select(bson.M{OutParam.SubModel(): 1, "_id": 1}).Limit(1)140 if selectRet == nil {141 err = Log.RetError("[mgo] selectRet invalid, submodule: %v.", OutParam.SubModel())142 return143 }144 outval := reflect.MakeMap(reflect.MapOf(reflect.TypeOf(""), reflect.TypeOf(OutParam)))145 ret = selectRet.One(outval.Interface())146 if ret != nil {147 err = Log.RetError("[mgo] select one error: %v.", ret)148 return149 }150 retIdxVal := outval.MapIndex(reflect.ValueOf(OutParam.SubModel()))151 if !retIdxVal.IsValid() {152 err = Log.RetError("[mgo] outval MapIndex invalid.")153 return154 }155 reflect.ValueOf(OutParam).Elem().Set(retIdxVal.Elem())156 exist = true157 return158}159func (this *TAokoMgo) QuerySome(Identify string, OutParam IDBCache) (err error) {160 session, err := this.GetMgoSession()161 if err != nil {162 return err163 }164 s := session.Clone()165 defer s.Close()166 collection := s.DB(this.server).C(OutParam.MainModel())167 err = collection.Find(bson.M{"_id": Identify}).All(&OutParam)168 if err != nil {169 err = fmt.Errorf("Identify: %v, MainModel: %v, SubModel: %v, err: %v.\n", Identify, OutParam.MainModel(), OutParam.SubModel(), err)170 Log.Error("[QuerySome] err: %v.\n", err)171 }172 return173}174func (this *TAokoMgo) InsertOne(Identify string, InParam IDBCache) (err error) {175 session, err := this.GetMgoSession()176 if err != nil {177 return err178 }179 s := session.Clone()180 defer s.Close()181 Log.FmtPrintf("[Insert] main: %v, sub: %v, key: %v.", InParam.MainModel(), InParam.SubModel(), InParam.Identify())182 collection := s.DB(this.server).C(InParam.MainModel())183 operAction := bson.M{"_id": InParam.Identify(), InParam.SubModel(): InParam}184 err = collection.Insert(operAction)185 if err != nil {186 err = fmt.Errorf("main: %v, sub: %v, key: %v, err: %v.\n", InParam.MainModel(), InParam.SubModel(), InParam.Identify(), err)187 Log.Error("[Insert] err: %v.\n", err)188 }189 return190}191func (this *TAokoMgo) SaveOne(Identify string, InParam IDBCache) (err error) {192 session, err := this.GetMgoSession()193 if err != nil {194 return err195 }196 redkey := MakeMgoModel(InParam.Identify(), InParam.MainModel(), InParam.SubModel())197 err = Save(session, this.server, redkey, InParam)198 return199}200func Save(mgosession *mgo.Session, dbserver, redkey string, data interface{}) (err error) {201 s := mgosession.Clone()202 defer s.Close()203 key, main, sub := RedisConn.ParseRedisKey(redkey)204 Log.FmtPrintf("update origin: %v, main: %v, sub: %v, key: %v.", redkey, main, sub, key)205 collection := s.DB(dbserver).C(main)206 operAction := bson.M{"$set": bson.M{sub: data}}207 _, err = collection.UpsertId(key, operAction)208 if err != nil {209 err = fmt.Errorf("main: %v, sub: %v, key: %v, err: %v.\n", main, sub, key, err)210 Log.Error("[Save] err: %v.\n", err)211 }212 return213}214func (this *TAokoMgo) EnsureIndex(InParam IDBCache, idxs []string) (err error) {215 session, err := this.GetMgoSession()216 if err != nil {217 return err218 }219 s := session.Clone()220 defer s.Close()221 c := s.DB(this.server).C(InParam.SubModel())222 err = c.EnsureIndex(mgo.Index{Key: idxs})223 return err224}...
dbmethods.go
Source:dbmethods.go
...4 "gopkg.in/mgo.v2"5)6//Controller represents controller's struct7type Controller struct {8 session *mgo.Session9}10//NewController initializes new mgov2 connection11func NewController() (*Controller, error) {12 session, err := mgo.Dial("mongodb://localhost:27017")13 if err != nil {14 return nil, err15 }16 session.SetMode(mgo.Monotonic, true)17 return &Controller{18 session: session,19 }, nil20}21func (ctl *Controller) getArticle(id string) (res Article) {22 session := ctl.session.Clone()23 defer session.Close()24 col := session.DB("main").C("articles")25 err := col.FindId(id).One(&res)26 if err != nil {27 fmt.Println(err.Error())28 }29 return30}31func (ctl *Controller) getArticleComments(articleID string) (res []Comment) {32 session := ctl.session.Clone()33 defer session.Close()34 col := session.DB("main").C("comments")35 col.Find(obj{"articleId": articleID}).All(&res)36 return37}38func (ctl *Controller) addUser(u User) {39 session := ctl.session.Clone()40 defer session.Close()41 col := session.DB("main").C("users")42 col.Insert(u)43}44func (ctl *Controller) getUser(id string) (u User) {45 session := ctl.session.Clone()46 defer session.Close()47 col := session.DB("main").C("users")48 fmt.Println("nickname ", id)49 col.Find(obj{"_id": id}).One(&u)50 return51}52func (ctl *Controller) getAllUsers() (usrs []User) {53 session := ctl.session.Clone()54 defer session.Close()55 col := session.DB("main").C("users")56 col.Find(obj{}).All(&usrs)57 return58}59func (ctl *Controller) deleteUser(id string) {60 session := ctl.session.Clone()61 defer session.Close()62 col := session.DB("main").C("users")63 col.RemoveId(id)64}65func (ctl *Controller) getArticles() (articles []Article) {66 session := ctl.session.Clone()67 defer session.Close()68 col := session.DB("main").C("articles")69 err := col.Find(obj{}).All(&articles)70 if err != nil {71 fmt.Println(err.Error())72 }73 return74}75func (ctl *Controller) addComment(comment Comment) {76 session := ctl.session.Clone()77 defer session.Close()78 col := session.DB("main").C("comments")79 col.Insert(comment)80}81func (ctl *Controller) addArticle(article Article) Article {82 session := ctl.session.Clone()83 defer session.Close()84 col := session.DB("main").C("articles")85 col.Insert(article)86 return article87}88func (ctl *Controller) updateUser(user User) {89 session := ctl.session.Clone()90 defer session.Close()91 col := session.DB("main").C("users")92 col.Update(93 obj{"_id": user.Nickname},94 obj{95 "$set": obj{96 "firstname": user.Firstname,97 "lastname": user.Lastname,98 "age": user.Age,99 "bicycle": user.Bicycle,100 },101 })102}103func (ctl *Controller) updateRates(id, nickname, rate string) {104 session := ctl.session.Clone()105 defer session.Close()106 col := session.DB("main").C("articles")107 fmt.Println(id, nickname, rate)108 col.Update(obj{"_id": id}, obj{"$set": obj{fmt.Sprintf("rates.%v", nickname): rate}})109}110func (ctl *Controller) editArticle(id, content string) {111 session := ctl.session.Clone()112 defer session.Close()113 col := session.DB("main").C("articles")114 col.Update(obj{"_id": id}, obj{"$set": obj{"content": content}})115}116func (ctl *Controller) deleteArticle(id string) {117 session := ctl.session.Clone()118 defer session.Close()119 col := session.DB("main").C("articles")120 col.RemoveId(id)121}...
session
Using AI Code Generation
1import (2func main() {3 http.HandleFunc("/", foo)4 http.HandleFunc("/bar", bar)5 http.Handle("/favicon.ico", http.NotFoundHandler())6 http.ListenAndServe(":8080", nil)7}8func foo(res http.ResponseWriter, req *http.Request) {9 fmt.Println("foo ran")10}11func bar(res http.ResponseWriter, req *http.Request) {12 fmt.Println("bar ran")13}
session
Using AI Code Generation
1import (2var session = map[string]int{}3func init() {4 tpl = template.Must(template.ParseGlob("templates/*"))5}6func main() {7 http.HandleFunc("/", index)8 http.HandleFunc("/dog", dog)9 http.HandleFunc("/me", me)10 http.Handle("/favicon.ico", http.NotFoundHandler())11 http.ListenAndServe(":8080", nil)12}13func index(w http.ResponseWriter, r *http.Request) {14 c, err := r.Cookie("my-cookie")15 if err != nil {16 c = &http.Cookie{17 }18 }19 c.Value = fmt.Sprint(x)20 http.SetCookie(w, c)21 tpl.ExecuteTemplate(w, "index.gohtml", c.Value)22}23func dog(w http.ResponseWriter, r *http.Request) {24 c, err := r.Cookie("my-cookie")25 if err != nil {26 log.Println(err)27 http.Redirect(w, r, "/", http.StatusSeeOther)28 }29 c.Value = fmt.Sprint(x)30 http.SetCookie(w, c)31 tpl.ExecuteTemplate(w, "dog.gohtml", c.Value)32}33func me(w http.ResponseWriter, r *http.Request) {34 c, err := r.Cookie("my-cookie")35 if err != nil {36 log.Println(err)37 http.Redirect(w, r, "/", http.StatusSeeOther)38 }39 c.Value = fmt.Sprint(x)40 http.SetCookie(w, c)41 tpl.ExecuteTemplate(w, "me.gohtml", c.Value)42}
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!!