creating room and client models
This commit is contained in:
parent
413f8f16d4
commit
c3765c66d0
|
@ -0,0 +1,38 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
// client represents a single chatting user
|
||||
type client struct {
|
||||
// socket is the web socket for this client
|
||||
socket *websocket.Conn
|
||||
|
||||
// send is a channel on which messages are sent
|
||||
send chan []byte
|
||||
|
||||
// room is the romm this client is chatting in.
|
||||
room *room
|
||||
}
|
||||
|
||||
func (c *client) read() {
|
||||
for {
|
||||
if _, msg, err := c.socket.ReadMessage(); err == nil {
|
||||
c.room.forward <- msg
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
c.socket.Close()
|
||||
}
|
||||
|
||||
func (c *client) write() {
|
||||
for msg := range c.send {
|
||||
if err := c.socket.WriteMessage(websocket.TextMessage, msg); err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
c.socket.Close()
|
||||
}
|
2
main.go
2
main.go
|
@ -28,7 +28,7 @@ func NewTemplateHandler() *templateHandler {
|
|||
}
|
||||
|
||||
func main() {
|
||||
http.HandleFunc("/", NewTemplateHandler().ServeHTTP)
|
||||
http.Handle("/", &templateHandler{filename: "chat.html"})
|
||||
|
||||
// start the web server
|
||||
if err := http.ListenAndServe(":8080", nil); err != nil {
|
||||
|
|
|
@ -0,0 +1,16 @@
|
|||
package main
|
||||
|
||||
type room struct {
|
||||
// forward is a channel that holds incoming mesages
|
||||
// that should be forwared to the other clients
|
||||
forward chan []byte
|
||||
|
||||
// join is a channel for clients wishing to join the room.
|
||||
join chan *client
|
||||
|
||||
// leave is a channel for clients wishing to leave the room
|
||||
leave chan *client
|
||||
|
||||
// clients holds all currents clients in this room
|
||||
clients map[*client]bool
|
||||
}
|
Loading…
Reference in New Issue