Created
December 8, 2012 08:12
-
-
Save sunfmin/4239211 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"code.google.com/p/go.net/websocket" | |
// "io" | |
"log" | |
"net/http" | |
) | |
type Room struct { | |
Id string | |
Sockets []*websocket.Conn | |
} | |
var Rooms = []Room{} | |
func MyRoom(id string, ws *websocket.Conn) (r Room) { | |
for _, room := range Rooms { | |
if room.Id == id { | |
r = room | |
break | |
} | |
} | |
r.Id = id | |
r.Sockets = append(r.Sockets, ws) | |
Rooms = append(Rooms, r) | |
return | |
} | |
func (r Room) BroadCast(message string) (err error) { | |
for _, ws := range r.Sockets { | |
websocket.Message.Send(ws, message) | |
} | |
return | |
} | |
func (r Room) RemoveConnection(ws *websocket.Conn) (err error) { | |
newsockets := []*websocket.Conn{} | |
for _, s := range r.Sockets { | |
if s != ws { | |
newsockets = append(newsockets, s) | |
} | |
} | |
r.Sockets = newsockets | |
return | |
} | |
func Connect(ws *websocket.Conn) { | |
room := MyRoom(ws.Request().FormValue("url"), ws) | |
for { | |
var message string | |
err := websocket.Message.Receive(ws, &message) | |
if err != nil { | |
log.Println(err) | |
break | |
} | |
log.Println(message) | |
room.BroadCast(message) | |
} | |
room.RemoveConnection(ws) | |
} | |
func main() { | |
http.Handle("/connect", websocket.Handler(Connect)) | |
err := http.ListenAndServe(":12345", nil) | |
if err != nil { | |
log.Fatal("ListenAndServe: ", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment