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
type Client struct {
  conn net.Conn
  isClose bool
  wg *sync.WaitGroup
}
 
func (c *Client) loop() {
  inputCh := c.input()
  sendCh := c.send()
  readCh := c.read()
  printCh := c.print()
 
  for { 
    select {
      case msg := <- inputCh:
        if msg == "quit" {
          c.isClose = true
          break
        }
        sendCh <- msg
      case msg := <-readCh:
        printCh <- msg
    }
  }
 
  c.wg.Wait()
  fmt.Println("client exit.")
}
 
func (c *Client) input() (chan string) {
  ch := make(chan string)
  
  c.wg.Add(1)
  go func(c *Client) {
    reader := bufio.NewReader(os.Stdin)
    for !c.isClose {
      fmt.Print("please input your message: ")
      msg, _, err := reader.ReadLine()
      if err != nil {
        panic(err)
      }
      ch <- msg
    }
  }(c)
 
  return ch
}
 
func (c *Client) send() (chan string) {
  ch := make(chan string)
  
  c.wg.Add(1)
  go func(c *Client) {
    for !c.isClose {
      n, err := c.conn.Write([]byte(<-ch))
      if err != nil {
        panic(err)
      }
      fmt.Println(n, "bytes sended.")
    }
  }(c)
 
  return ch
}
 
func (c *Client) read() (chan string) {
  ch := make(chan string)
  
  c.wg.Add(1)
  go func(c *Client) {
    reader := bufio.NewReader(c.conn)
    for !c.isClose {
      // need to set timeout
      msg, _, err := reader.ReadLine()
      if err != nil {
        panic(err)
      }
      ch <- msg
    }(c)
  }
  
  return ch
}
 
func (c *Client) print() (chan string) {
  ch := make(chan string)
 
  c.wg.Add(1)
  go func(c *Client) {
    for !c.isClose {
      fmt.Println("received message:"<-ch)
    }
  }
 
  return ch
}
cs



폰으로 중요 메소드만 대충 짠거라 컴파일은 안될건데


go에서 논블록킹 io 저렇게 구현하면됨??


goroutine들 띄워놓고 loop 메소드에서 for-select 돌리면서 처리하게했는데


내가 궁금한건 각 goroutine들을 멤버 bool 변수 isClose로 죽이는게 최선의 방법인지??