最近写了一个chrome的websocket extension,server端用的是Java的Netty框架,后来发现golang 实现websocket 非常简单,高效, 下面是例子, 简单实现了用户登录,广播,相当于聊天室!
- packagemain
- import(
- "code.google.com/p/go.net/websocket"
- "html/template"
- "log"
- "net/http"
- "os"
- "strings"
- "time"
- )
- const(
- listenAddr="localhost:9527"//serveraddress
- )
- var(
- pwd,_=os.Getwd()
- RootTemp=template.Must(template.ParseFiles(pwd+"/chat.html"))
- JSON=websocket.JSON//codecforJSON
- Message=websocket.Message//codecforstring,[]byte
- ActiveClients=make(map[ClientConn]string)//mapcontainingclients
- User=make(map[string]string)
- )
- //Initializehandlersandwebsockethandlers
- funcinit(){
- User["aaa"]="aaa"
- User["bbb"]="bbb"
- User["test"]="test"
- User["test2"]="test2"
- User["test3"]="test3"
- }
- //Clientconnectionconsistsofthewebsocketandtheclientip
- typeClientConnstruct{
- websocket*websocket.Conn
- clientIPstring
- }
- //WebSocketservertohandlechatbetweenclients
- funcSockServer(ws*websocket.Conn){
- varerrerror
- varclientMessagestring
- //use[]byteifwebsocketbinarytypeisbloborarraybuffer
- //varclientMessage[]byte
- //cleanuponserverside
- deferfunc(){
- iferr=ws.Close();err!=nil{
- log.Println("Websocketcouldnotbeclosed",err.Error())
- }
- }()
- client:=ws.Request().RemoteAddr
- log.Println("Clientconnected:",client)
- sockCli:=ClientConn{ws,client}
- ActiveClients[sockCli]=""
- log.Println("Numberofclientsconnected:",len(ActiveClients))
- //forloopsothewebsocketstaysopenotherwise
- //it'llcloseafteroneReceieveandSend
- for{
- iferr=Message.Receive(ws,&clientMessage);err!=nil{
- //IfwecannotReadthentheconnectionisclosed
- log.Println("WebsocketDisconnectedwaiting",err.Error())
- //removethewsclientconnfromouractiveclients
- delete(ActiveClients,sockCli)
- log.Println("Numberofclientsstillconnected:",len(ActiveClients))
- return
- }
- varmsg_arr=strings.Split(clientMessage,"|")
- ifmsg_arr[0]=="login"&&len(msg_arr)==3{
- name:=msg_arr[1]
- pass:=msg_arr[2]
- ifpass==User[name]{
- ActiveClients[sockCli]=name
- iferr=Message.Send(ws,"login|"+name);err!=nil{
- log.Println("Couldnotsendmessageto",client,err.Error())
- }
- }else{
- log.Println("loginfaild:",clientMessage)
- }
- }elseifmsg_arr[0]=="msg"{
- ifActiveClients[sockCli]!=""{
- clientMessage="msg|"+time.Now().Format("2006-01-0215:04:05")+""+ActiveClients[sockCli]+"Said:"+msg_arr[1]
- forcs,na:=rangeActiveClients{
- ifna!=""{
- iferr=Message.Send(cs.websocket,clientMessage);err!=nil{
- log.Println("Couldnotsendmessageto",cs.clientIP,err.Error())
- }
- }
- }
- }
- }
- }
- }
- //RootHandlerrendersthetemplatefortherootpage
- funcRootHandler(whttp.ResponseWriter,req*http.Request){
- err:=RootTemp.Execute(w,listenAddr)
- iferr!=nil{
- http.Error(w,err.Error(),http.StatusInternalServerError)
- }
- }
- funcmain(){
- http.HandleFunc("/",RootHandler)
- http.Handle("/socket",websocket.Handler(SockServer))
- err:=http.ListenAndServe(listenAddr,nil)
- iferr!=nil{
- panic("ListenAndServe:"+err.Error())
- }
- }