先说点无关的,最近忙于工作没有更新博客,今天休息顺便把golang websocket研究了一下,挺好玩的,写了一个聊天室,分享给大家.
package main
import (
"fmt"
"io"
"bufio"
"net/http"
"code.google.com/p/go.net/websocket"
"container/list"
)
var connid int
var conns *list.List
func ChatroomServer(ws *websocket.Conn) {
defer ws.Close()
connid++
id := connid
fmt.Printf("connection id: %d\n", id)
item := conns.PushBack(ws)
defer conns.Remove(item)
name := fmt.Sprintf("user%d", id)
SendMessage(nil, fmt.Sprintf("welcome %s join\n", name))
r := bufio.NewReader(ws)
for {
data, err := r.ReadBytes('\n')
if err != nil {
fmt.Printf("disconnected id: %d\n", id)
SendMessage(item, fmt.Sprintf("%s offline\n", name))
break
}
fmt.Printf("%s: %s", name, data)
SendMessage(item, fmt.Sprintf("%s\t> %s", name, data))
}
}
func SendMessage(self *list.Element, data string) {
// for _, item := range conns {
for item := conns.Front(); item != nil; item = item.Next() {
ws, ok := item.Value.(*websocket.Conn)
if !ok {
panic("item not *websocket.Conn")
}
if item == self {
continue
}
io.WriteString(ws, data)
}
}
// 网页客户端
func Client(w http.ResponseWriter, r *http.Request) {
html := `
`
io.WriteString(w, html)
}
func main() {
fmt.Printf(`Welcome chatroom server!
author: dotcoo zhao
url: http://www.dotcoo.com/golang-websocket-chatroom
`)
cOnnid= 0
cOnns= list.New()
http.Handle("/chatroom", websocket.Handler(ChatroomServer));
http.HandleFunc("/", Client);
err := http.ListenAndServe(":6611", nil);
if err != nil {
panic("ListenAndServe: " + err.Error())
}
}
简陋了些,但是基本功能都有了.