Best Gauge code snippet using conn.processMessage
peer.go
Source:peer.go
1// Copyright 2018 The Gringo Developers. All rights reserved.2// Use of this source code is governed by a GNU GENERAL PUBLIC LICENSE v33// license that can be found in the LICENSE file.4package p2p5import (6 "bufio"7 "bytes"8 "encoding/hex"9 "errors"10 "fmt"11 "github.com/dblokhin/gringo/consensus"12 "github.com/sirupsen/logrus"13 "io"14 "net"15 "sync"16 "sync/atomic"17)18// Peer is a participant of p2p network19type Peer struct {20 conn net.Conn21 sync *Syncer22 // The following fields are only meant to be used *atomically*23 bytesReceived uint6424 bytesSent uint6425 quit chan struct{}26 wg sync.WaitGroup27 // Queue for sending message28 sendQueue chan Message29 // disconnect flag30 disconnect int3231 // Network addr32 Addr string33 // Info connected peer34 Info struct {35 // protocol version of the sender36 Version uint3237 // capabilities of the sender38 Capabilities consensus.Capabilities39 // total difficulty accumulated by the sender, used to check whether sync40 // may be needed41 TotalDifficulty consensus.Difficulty42 // name of version of the software43 UserAgent string44 // Height45 Height uint6446 }47}48// NewPeer connects to peer49func NewPeer(sync *Syncer, addr string) (*Peer, error) {50 logrus.Infof("starting new peer (%s)", addr)51 tcpAddr, err := net.ResolveTCPAddr("tcp", addr)52 if err != nil {53 return nil, err54 }55 // dial connection56 conn, err := net.DialTCP("tcp", nil, tcpAddr)57 if err != nil {58 return nil, err59 }60 logrus.Infof("connected to peer (%s)", addr)61 shake, err := shakeByHand(conn)62 if err != nil {63 return nil, err64 }65 p := new(Peer)66 p.conn = conn67 p.sync = sync68 p.quit = make(chan struct{})69 p.sendQueue = make(chan Message)70 // Store the network addr71 p.Addr = addr72 p.Info.Version = shake.Version73 p.Info.Capabilities = shake.Capabilities74 p.Info.TotalDifficulty = shake.TotalDifficulty75 p.Info.UserAgent = shake.UserAgent76 return p, nil77}78// AcceptNewPeer creates peer accepting listening server conn79func AcceptNewPeer(conn net.Conn) (*Peer, error) {80 logrus.Info("accept new peer")81 hand, err := handByShake(conn)82 if err != nil {83 return nil, err84 }85 p := new(Peer)86 p.conn = conn87 p.quit = make(chan struct{})88 p.sendQueue = make(chan Message)89 p.Info.Version = hand.Version90 p.Info.Capabilities = hand.Capabilities91 p.Info.TotalDifficulty = hand.TotalDifficulty92 p.Info.UserAgent = hand.UserAgent93 return p, nil94}95// Start starts loop listening, write handler and so on96func (p *Peer) Start() {97 p.wg.Add(2)98 go p.writeHandler()99 go p.readHandler()100}101// writeHandler is a goroutine dedicated to reading messages off of an incoming102// queue, and writing them out to the wire.103//104// NOTE: This method MUST be run as a goroutine.105func (p *Peer) writeHandler() {106 var exitError error107out:108 for {109 select {110 case msg := <-p.sendQueue:111 // Ensure that conn is alive112 if atomic.LoadInt32(&p.disconnect) != 0 {113 break out114 }115 var written uint64116 if written, exitError = WriteMessage(p.conn, msg); exitError != nil {117 break out118 }119 atomic.AddUint64(&p.bytesSent, written)120 case <-p.quit:121 exitError = errors.New("peer exiting")122 break out123 }124 }125 p.wg.Done()126 p.Disconnect(exitError)127}128// WriteMessage places msg to send queue129func (p *Peer) WriteMessage(msg Message) {130 select {131 case <-p.quit:132 logrus.Info("cannot send message, peer is shutting down")133 case p.sendQueue <- msg:134 }135}136// readHandler is responsible for reading messages off the wire in series, then137// properly dispatching the handling of the message to the proper subsystem.138//139// NOTE: This method MUST be run as a goroutine.140func (p *Peer) readHandler() {141 var exitError error142 input := bufio.NewReader(p.conn)143 header := new(Header)144out:145 for atomic.LoadInt32(&p.disconnect) == 0 {146 if exitError = header.Read(input); exitError != nil {147 logrus.Debugf("Failed to read message from peer %v", p.conn.RemoteAddr())148 break out149 }150 if header.Len > consensus.MaxMsgLen {151 exitError = errors.New("too big message size")152 break out153 }154 // Read the whole message. If the peer disconnects mid-way through155 // ReadFull will return an error.156 readBuffer := make([]byte, header.Len)157 _, err := io.ReadFull(input, readBuffer)158 if err != nil {159 logrus.Infof("Failed to read message: %v", err)160 break out161 }162 // Print the message for debugging purposes.163 logrus.Debugf("Received message from %s: %02x%02x", p.conn.RemoteAddr(), header.Bytes(), readBuffer)164 rl := bytes.NewReader(readBuffer)165 switch header.Type {166 case consensus.MsgTypePing:167 // update peer info & send Pong168 var msg Ping169 if exitError = msg.Read(rl); exitError != nil {170 break out171 }172 logrus.Debugf("Received Ping from %s", p.conn.RemoteAddr().String())173 p.sync.ProcessMessage(p, &msg)174 case consensus.MsgTypePong:175 // update peer info176 var msg Pong177 if exitError = msg.Read(rl); exitError != nil {178 break out179 }180 p.sync.ProcessMessage(p, &msg)181 case consensus.MsgTypeGetPeerAddrs:182 logrus.Infof("receiving peer request (%s)", p.conn.RemoteAddr().String())183 var msg GetPeerAddrs184 if exitError = msg.Read(rl); exitError != nil {185 break out186 }187 p.sync.ProcessMessage(p, &msg)188 case consensus.MsgTypePeerAddrs:189 logrus.Infof("receiving peer addrs (%s)", p.conn.RemoteAddr().String())190 var msg PeerAddrs191 if exitError = msg.Read(rl); exitError != nil {192 break out193 }194 logrus.Infof("received %d peers", len(msg.peers))195 p.sync.ProcessMessage(p, &msg)196 case consensus.MsgTypeGetHeaders:197 logrus.Infof("receiving header request (%s)", p.conn.RemoteAddr().String())198 var msg GetBlockHeaders199 if exitError = msg.Read(rl); exitError != nil {200 break out201 }202 p.sync.ProcessMessage(p, &msg)203 case consensus.MsgTypeHeader:204 logrus.Infof("header notification from peer %s", p.conn.RemoteAddr().String())205 var msg BlockHeader206 if exitError = msg.Read(rl); exitError != nil {207 break out208 }209 p.sync.ProcessMessage(p, &msg)210 case consensus.MsgTypeHeaders:211 logrus.Infof("receiving headers (%s)", p.conn.RemoteAddr().String())212 var msg BlockHeaders213 if exitError = msg.Read(rl); exitError != nil {214 break out215 }216 logrus.Debug("headers: ", msg.Headers)217 p.sync.ProcessMessage(p, &msg)218 case consensus.MsgTypeGetBlock:219 logrus.Infof("receiving block request (%s)", p.conn.RemoteAddr().String())220 var msg GetBlock221 if exitError = msg.Read(rl); exitError != nil {222 break out223 }224 p.sync.ProcessMessage(p, &msg)225 case consensus.MsgTypeBlock:226 logrus.Infof("receiving block (%s)", p.conn.RemoteAddr().String())227 var msg consensus.Block228 if exitError = msg.Read(rl); exitError != nil {229 break out230 }231 logrus.Info("block hash: ", hex.EncodeToString(msg.Header.Hash()))232 p.sync.ProcessMessage(p, &msg)233 case consensus.MsgTypeGetCompactBlock:234 logrus.Infof("receiving compact block request (%s)", p.conn.RemoteAddr().String())235 // TODO: impl it236 case consensus.MsgTypeCompactBlock:237 logrus.Infof("receiving compact block (%s)", p.conn.RemoteAddr().String())238 var msg consensus.CompactBlock239 if exitError = msg.Read(rl); exitError != nil {240 break out241 }242 // TODO: process compact block243 logrus.Info("compact block hash: ", hex.EncodeToString(msg.Header.Hash()))244 case consensus.MsgTypeTransaction:245 logrus.Infof("receiving transaction (%s)", p.conn.RemoteAddr().String())246 var msg consensus.Transaction247 if exitError = msg.Read(rl); exitError != nil {248 break out249 }250 logrus.Debug("transaction: ", msg)251 p.sync.ProcessMessage(p, &msg)252 default:253 // Print the content of the unknown message.254 buff := make([]byte, header.Len)255 if _, err := io.ReadFull(rl, buff); err != nil {256 logrus.Debugf("failed to read message body: %v", err)257 break out258 }259 logrus.Debugf("received unexpected message: %02x%02x", header.Bytes(), buff)260 exitError = fmt.Errorf("received unexpected message from peer: %v", header)261 break out262 }263 // update recv bytes counter264 atomic.AddUint64(&p.bytesReceived, header.Len+consensus.HeaderLen)265 }266 p.wg.Done()267 p.Disconnect(exitError)268}269// Disconnect closes peer connection270func (p *Peer) Disconnect(reason error) {271 if !atomic.CompareAndSwapInt32(&p.disconnect, 0, 1) {272 return273 }274 logrus.Info("Disconnect peer: ", reason)275 close(p.quit)276 p.conn.Close()277 p.wg.Wait()278}279// Close the connection to the remote peer280func (p *Peer) Close() {281 p.Disconnect(errors.New("closing peer"))282}283// WaitForDisconnect waits until the peer has disconnected.284func (p *Peer) WaitForDisconnect() {285 <-p.quit286 p.wg.Wait()287}288// SendPing sends Ping request to peer289func (p *Peer) SendPing() {290 logrus.Infof("Sending Ping to %s", p.conn.RemoteAddr())291 var request Ping292 request.TotalDifficulty = consensus.Difficulty(1)293 request.Height = 1294 p.WriteMessage(&request)295}296// SendBlockRequest sends request block by hash297func (p *Peer) SendBlockRequest(hash consensus.Hash) {298 logrus.Infof("sending block request (%s)", hex.EncodeToString(hash[:6]))299 var request GetBlock300 request.Hash = hash301 p.WriteMessage(&request)302}303// SendBlock sends Block to peer304func (p *Peer) SendBlock(block *consensus.Block) {305 logrus.Info("sending block, height: ", block.Header.Height)306 p.WriteMessage(block)307}308// SendPeerRequest sends peer request309func (p *Peer) SendPeerRequest(capabilities consensus.Capabilities) {310 logrus.Infof("Sending GetPeerAddrs to %s", p.conn.RemoteAddr())311 var request GetPeerAddrs312 request.Capabilities = capabilities313 p.WriteMessage(&request)314}315// SendHeaderRequest sends request headers316func (p *Peer) SendHeaderRequest(locator consensus.Locator) {317 logrus.Info("sending headers request")318 if len(locator.Hashes) > consensus.MaxLocators {319 logrus.Debug("locator hashes count: ", len(locator.Hashes))320 logrus.Fatal(errors.New("too big locator hashes"))321 }322 var request GetBlockHeaders323 request.Locator = locator324 p.WriteMessage(&request)325}326// SendTransaction sends tx to peer327func (p *Peer) SendTransaction(tx consensus.Transaction) {328 logrus.Info("sending transaction")329 p.WriteMessage(&tx)330}...
clients.go
Source:clients.go
1package broker2import (3 "context"4 "errors"5 "net"6 "github.com/werbenhu/amqtt/ifs"7 "github.com/werbenhu/amqtt/logger"8 "github.com/werbenhu/amqtt/packets"9)10type Client struct {11 id string12 conn net.Conn13 ctx context.Context14 cancelFunc context.CancelFunc15 topics map[string]interface{}16 typ int17 will *packets.PublishPacket18}19func NewClient(conn net.Conn, typ int) ifs.Client {20 c := new(Client)21 c.conn = conn22 c.typ = typ23 c.topics = make(map[string]interface{})24 c.ctx, c.cancelFunc = context.WithCancel(context.Background())25 return c26}27func (c *Client) ReadLoop(processor ifs.Processor) {28 for {29 select {30 case <-c.ctx.Done():31 return32 default:33 packet, err := c.ReadPacket()34 if err != nil {35 logger.Debugf("Client ReadLoop read packet error: %+v\n", err)36 // if the client has disconnected ungracefully.37 // the broker sends the last-will message to all subscribed clients of the last-will message topic.38 // å¦æè¿æ¥å¼å¸¸ï¼è¦åééå±æ¶æ¯ç»ææ订é
äºè¯¥éå±æ¶æ¯ä¸»é¢çææ客æ·ç«¯39 if c.will != nil {40 processor.ProcessMessage(c, c.will)41 }42 packet := packets.NewControlPacket(packets.Disconnect).(*packets.DisconnectPacket)43 processor.ProcessMessage(c, packet)44 return45 }46 processor.ProcessMessage(c, packet)47 }48 }49}50func (c *Client) SetWill(will *packets.PublishPacket) {51 c.will = will52}53func (c *Client) SetId(id string) ifs.Client {54 c.id = id55 return c56}57func (c *Client) SetConn(conn net.Conn) ifs.Client {58 c.conn = conn59 return c60}61func (c *Client) GetId() string {62 return c.id63}64func (c *Client) GetConn() net.Conn {65 return c.conn66}67func (c *Client) GetTyp() int {68 return c.typ69}70func (c *Client) ReadPacket() (packets.ControlPacket, error) {71 if c.conn != nil {72 packet, err := packets.ReadPacket(c.conn)73 return packet, err74 }75 return nil, errors.New("CONN IS DISCONNECTED")76}77func (c *Client) WritePacket(packet packets.ControlPacket) error {78 if c.conn != nil {79 err := packet.Write(c.conn)80 return err81 }82 return nil83}84func (c *Client) Topics() map[string]interface{} {85 return c.topics86}87func (c *Client) AddTopic(topic string, data interface{}) (exist bool) {88 if _, ok := c.topics[topic]; ok {89 exist = true90 }91 c.topics[topic] = data92 return93}94func (c *Client) RemoveTopic(topic string) error {95 if _, ok := c.topics[topic]; !ok {96 return errors.New("TOPIC NOT EXIST")97 }98 delete(c.topics, topic)99 return nil100}101func (c *Client) Done() <-chan struct{} {102 return c.ctx.Done()103}104func (c *Client) Close() error {105 c.cancelFunc()106 var err error107 if c.conn != nil {108 err = c.conn.Close()109 c.conn = nil110 }111 return err112}...
client.go
Source:client.go
1package guardface2import (3 "context"4 "sync"5 "time"6 "github.com/haobird/logger"7)8const (9 Connected = 110 Disconnected = 211)12//Client 客æ·ç«¯ï¼è®¾å¤ï¼13type Client struct {14 ID string15 status int // ç¶æ16 mu sync.Mutex17 ctx context.Context18 cancelFunc context.CancelFunc19 conn *ProtoConn20 keepalive int // çå½å¨æ å¤å°ç§21 wmsgs chan []byte // åéæ°æ®22 beforeCloseHandler func(string)23 msgHandler func(*Package)24}25// NewClient å建客æ·ç«¯26func NewClient(key string, conn *ProtoConn) *Client {27 ctx, cancelFunc := context.WithCancel(context.Background())28 return &Client{29 ID: key,30 conn: conn,31 keepalive: lifeSpan,32 wmsgs: make(chan []byte, 100),33 ctx: ctx,34 cancelFunc: cancelFunc,35 }36}37// æ§è¡ä¸å ä»»å¡38func (c *Client) dispatch() {39 for {40 select {41 case <-c.ctx.Done():42 return43 case buf := <-c.wmsgs:44 logger.Debugf("[%s]å¾è®¾å¤åå
¥æ°æ®:%s", c.ID, string(buf))45 c.Write(buf)46 }47 }48}49// Loop 循ç¯å¤ç50func (c *Client) Loop() {51 nc := c.conn52 if nc == nil {53 return54 }55 // æ§è¡ ä¸å ä»»å¡56 go c.dispatch()57 keepAlive := time.Second * time.Duration(c.keepalive)58 timeOut := keepAlive + (keepAlive / 2)59 for {60 select {61 case <-c.ctx.Done():62 return63 default:64 //add read timeout å deadlineæ¶é´ï¼å¦æ客æ·ç«¯æå¼è¿æ¥65 if keepAlive > 0 {66 if err := nc.SetReadDeadline(time.Now().Add(timeOut)); err != nil {67 logger.Errorf("[%s]set read timeout error: %s", c.ID, err)68 // msg := Message{69 // client: c,70 // packet: disconnectPack,71 // }72 // ProcessMessage(msg)73 // disconnectBuf, _ := json.Marshal(disconnectPack)74 // c.ProcessMessage(disconnectBuf)75 DisconnectHandler(c)76 return77 }78 }79 data, err := nc.ReadMessage()80 if err != nil {81 logger.Errorf("[%s]read packet error: %s", c.ID, err)82 // msg := Message{83 // client: c,84 // packet: disconnectPack,85 // }86 // disconnectBuf, _ := json.Marshal(disconnectPack)87 // c.ProcessMessage(disconnectBuf)88 DisconnectHandler(c)89 return90 }91 // c.ProcessMessage(data)92 ProcessRawData(c, data)93 }94 }95}96//Close å
³éè¿æ¥97func (c *Client) Close() {98 if c.status == Disconnected {99 return100 }101 c.cancelFunc()102 c.status = Disconnected103 if c.conn != nil {104 c.conn.Close()105 c.conn = nil106 }107}108//Write åå
¥è¿æ¥æ°æ®109func (c *Client) Write(buf []byte) error {110 return c.conn.WriteMessage(buf)111}...
processMessage
Using AI Code Generation
1conn.processMessage()2conn.processMessage()3conn.processMessage()4conn.processMessage()5conn.processMessage()6conn.processMessage()7conn.processMessage()8conn.processMessage()9conn.processMessage()10conn.processMessage()11conn.processMessage()12conn.processMessage()13conn.processMessage()14conn.processMessage()15conn.processMessage()16conn.processMessage()17conn.processMessage()18conn.processMessage()19conn.processMessage()20conn.processMessage()21conn.processMessage()22conn.processMessage()23conn.processMessage()
processMessage
Using AI Code Generation
1conn := new(conn)2conn.processMessage()3conn := new(conn)4conn.processMessage()5conn := new(conn)6conn.processMessage()
processMessage
Using AI Code Generation
1conn := new(conn)2conn.processMessage()3conn := new(conn)4conn.processMessage()5conn := new(conn)6conn.processMessage()7conn := new(conn)8conn.processMessage()9conn := new(conn)10conn.processMessage()11conn := new(conn)12conn.processMessage()13conn := new(conn)14conn.processMessage()15conn := new(conn)16conn.processMessage()17conn := new(conn)18conn.processMessage()19conn := new(conn)20conn.processMessage()21conn := new(conn)22conn.processMessage()23conn := new(conn)24conn.processMessage()25conn := new(conn)26conn.processMessage()27conn := new(conn)28conn.processMessage()29conn := new(conn)30conn.processMessage()31conn := new(conn)32conn.processMessage()33conn := new(conn)34conn.processMessage()35conn := new(conn)36conn.processMessage()37conn := new(conn)38conn.processMessage()
processMessage
Using AI Code Generation
1func main() {2 conn := new(conn)3 conn.processMessage()4}5func main() {6 conn := new(conn)7 conn.processMessage()8}9func main() {10 conn := new(conn)11 conn.processMessage()12}13import (14func main() {15 data, _ := ioutil.ReadAll(os.Stdin)16 req := new(plugin_go.CodeGeneratorRequest)17 proto.Unmarshal(data, req)18 resp := new(plugin_go.CodeGeneratorResponse)19 for _, protoFile := range req.ProtoFile {20 for _, service := range protoFile.Service {21 for _, method := range service.Method {22 fmt.Println(method.GetName())23 fmt.Println(method.GetInputType())24 fmt.Println(method.GetOutputType())25 }26 }27 }28 data, _ = proto.Marshal(resp)29 os.Stdout.Write(data)30}31import (32func main() {33 data, _ := ioutil.ReadAll(os.Stdin)34 req := new(plugin_go.CodeGeneratorRequest)35 proto.Unmarshal(data, req)36 resp := new(plugin_go.CodeGeneratorResponse)37 for _, protoFile := range req.ProtoFile {38 for _, service := range protoFile.Service {39 for _, method := range service.Method {40 fmt.Println(method.GetName())41 fmt.Println(method.GetInputType())42 fmt.Println(method.GetOutputType())43 }44 }45 }46 data, _ = proto.Marshal(resp)47 os.Stdout.Write(data)48}49import (
processMessage
Using AI Code Generation
1func main() {2 conn := new(conn)3 conn.processMessage()4}5func main() {6 conn := new(conn)7 conn.processMessage()8}9func main() {10 conn := new(conn)11 conn.processMessage()12}13func main() {14 conn := new(conn)15 conn.processMessage()16}17func main() {18 conn := new(conn)19 conn.processMessage()20}21func main() {22 conn := new(conn)23 conn.processMessage()24}25func main() {26 conn := new(conn)27 conn.processMessage()28}29func main() {30 conn := new(conn)31 conn.processMessage()32}33func main() {34 conn := new(conn)35 conn.processMessage()36}37func main() {38 conn := new(conn)39 conn.processMessage()40}41func main() {42 conn := new(conn)43 conn.processMessage()44}45func main() {46 conn := new(conn)47 conn.processMessage()48}49func main() {50 conn := new(conn)51 conn.processMessage()52}53func main() {54 conn := new(conn)55 conn.processMessage()56}57func main() {58 conn := new(conn)59 conn.processMessage()60}
processMessage
Using AI Code Generation
1conn.processMessage("Hello World")2conn.processMessage("Hello World")3conn.processMessage("Hello World")4conn.processMessage("Hello World")5conn.processMessage("Hello World")6conn.processMessage("Hello World")7conn.processMessage("Hello World")8conn.processMessage("Hello World")9conn.processMessage("Hello World")10conn.processMessage("Hello World")11conn.processMessage("Hello World")12conn.processMessage("Hello World")13conn.processMessage("Hello World")14conn.processMessage("Hello World")15conn.processMessage("Hello World")16conn.processMessage("Hello World")17conn.processMessage("Hello World")18conn.processMessage("Hello World")19conn.processMessage("Hello World")20conn.processMessage("Hello World")
processMessage
Using AI Code Generation
1conn.processMessage("Hello World")2conn.processMessage("Hello World")3conn.processMessage("Hello World")4conn.processMessage("Hello World")5conn.processMessage("Hello World")6conn.processMessage("Hello World")7conn.processMessage("Hello World")8conn.processMessage("Hello World")9conn.processMessage("Hello World")10conn.processMessage("Hello World")11conn.processMessage("Hello World")12conn.processMessage("Hello World")13conn.processMessage("Hello World")14conn.processMessage("Hello World")15conn.processMessage("Hello World")16conn.processMessage("Hello World")17conn.processMessage("Hello World")18conn.processMessage("Hello World")19conn.processMessage("Hello World")20conn.processMessage("
processMessage
Using AI Code Generation
1import (2func main() {3 ln, err := net.Listen("tcp", ":8080")4 if err != nil {5 fmt.Println(err)6 os.Exit(1)7 }8 defer ln.Close()9 fmt.Println("Listening on
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!!