Skip to content

Commit 5c72362

Browse files
Merge pull request #58 from ranjanraghavendra/patch-1
Added examples related to websocket
2 parents 4e18bce + c72e436 commit 5c72362

File tree

1 file changed

+111
-0
lines changed

1 file changed

+111
-0
lines changed

advanced/websocket_client.go

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
package chat
2+
3+
import (
4+
"fmt"
5+
"io"
6+
"log"
7+
8+
"golang.org/x/net/websocket"
9+
)
10+
11+
const channelBufSize = 100
12+
13+
var maxId int = 0
14+
15+
// Chat client.
16+
type Client struct {
17+
id int
18+
ws *websocket.Conn
19+
server *Server
20+
ch chan *Message
21+
doneCh chan bool
22+
}
23+
24+
// Create new chat client.
25+
func NewClient(ws *websocket.Conn, server *Server) *Client {
26+
27+
if ws == nil {
28+
panic("ws cannot be nil")
29+
}
30+
31+
if server == nil {
32+
panic("server cannot be nil")
33+
}
34+
35+
maxId++
36+
ch := make(chan *Message, channelBufSize)
37+
doneCh := make(chan bool)
38+
39+
return &Client{maxId, ws, server, ch, doneCh}
40+
}
41+
42+
func (c *Client) Conn() *websocket.Conn {
43+
return c.ws
44+
}
45+
46+
func (c *Client) Write(msg *Message) {
47+
select {
48+
case c.ch <- msg:
49+
default:
50+
c.server.Del(c)
51+
err := fmt.Print("client %d is disconnected.")
52+
c.server.Err(err)
53+
}
54+
}
55+
56+
func (c *Client) Done() {
57+
c.doneCh <- true
58+
}
59+
60+
// Listen Write and Read request via chanel
61+
func (c *Client) Listen() {
62+
go c.listenWrite()
63+
c.listenRead()
64+
}
65+
66+
// Listen write request via chanel
67+
func (c *Client) listenWrite() {
68+
log.Println("Listening write to client")
69+
for {
70+
select {
71+
72+
// send message to the client
73+
case msg := <-c.ch:
74+
log.Println("Send:", msg)
75+
websocket.JSON.Send(c.ws, msg)
76+
77+
// receive done request
78+
case <-c.doneCh:
79+
c.server.Del(c)
80+
c.doneCh <- true // for listenRead method
81+
return
82+
}
83+
}
84+
}
85+
86+
// Listen read request via chanel
87+
func (c *Client) listenRead() {
88+
log.Println("Listening read from client")
89+
for {
90+
select {
91+
92+
// receive done request
93+
case <-c.doneCh:
94+
c.server.Del(c)
95+
c.doneCh <- true // for listenWrite method
96+
return
97+
98+
// read data from websocket connection
99+
default:
100+
var msg Message
101+
err := websocket.JSON.Receive(c.ws, &msg)
102+
if err == io.EOF {
103+
c.doneCh <- true
104+
} else if err != nil {
105+
c.server.Err(err)
106+
} else {
107+
c.server.SendAll(&msg)
108+
}
109+
}
110+
}
111+
}

0 commit comments

Comments
 (0)