Blame view

components/net/conn.go 1.54 KB
fee11bff   zhangqijia   客户端无法使用grpc热更,不用g...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
  package net
  
  import (
  	"bufio"
  	"fmt"
  	"net"
  )
  
  type Head struct {
  	Length 		int32
  	Cmd 		int32
  	ErrCode 	int32
  	PreField    int32
  }
  
  
  type Connection struct {
  	net.Conn
  	Id int
  	Server *Server
  
  	scanner *bufio.Scanner
  	writer *bufio.Writer
  
  	WBuffer chan []byte
  	RBuffer chan *MsgPkg
  
  	Quit chan *Connection
  }
  
  type MsgPkg struct {
  	Head Head
  	Body []byte
  	Conn *Connection
  }
  
  func NewConn(id int, conn net.Conn, s *Server) *Connection {
  	return &Connection{
  		Id: id,
  		Conn: conn,
  		Server: s,
  
  		scanner: bufio.NewScanner(conn),
  		writer: bufio.NewWriter(conn),
  		WBuffer: make(chan []byte),
  		RBuffer: make(chan *MsgPkg),
  		Quit: make(chan *Connection),
  	}
  }
  
  func (c *Connection) write()  {
  	defer c.Quiting()
  
  	for msg := range c.WBuffer {
  		if _, err := c.writer.Write(msg); err != nil {
  			fmt.Println("write fail err: " + err.Error())
  			return
  		}
  		if err := c.writer.Flush(); err != nil {
  			fmt.Println("write Flush fail err: " + err.Error())
  			return
  		}
  	}
  }
  
  func (c *Connection) read() {
  	defer c.Quiting()
  	for  {
  		c.scanner.Split(ParseMsg)
  
  		for c.scanner.Scan() {
  			req, err := DecodeMsg(c.scanner.Bytes())
  			if err != nil {
  				return
  			}
  
  			req.Conn = c
  			c.Server.OnRecv(req)
  		}
  
  		if err := c.scanner.Err(); err != nil {
  			fmt.Printf("scanner.err: %s\n", err.Error())
  			c.Quiting()
  			return
  		}
  	}
  }
  
  func (c *Connection) Start()  {
  	go c.write()
  	go c.read()
  }
  
  func (c *Connection) Stop()  {
  	close(c.RBuffer)
  	close(c.WBuffer)
  	c.Conn.Close()
  }
  
  func (c *Connection) Quiting()  {
  	c.Server.OnClose(c)
  }
  
  func (c *Connection) SendMsg(){
  }