creating room and client models

This commit is contained in:
Fred 2016-10-01 21:57:41 +02:00
parent 413f8f16d4
commit c3765c66d0
4 changed files with 55 additions and 1 deletions

BIN
chat Executable file

Binary file not shown.

38
client.go Normal file
View File

@ -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()
}

View File

@ -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 {

16
room.go Normal file
View File

@ -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
}