golang基于websocket实现的简易聊天室程序
本文实例讲述了golang基于websocket实现的简易聊天室。分享给大家供大家参考,具体如下:
先说点无关的,最近忙于工作没有更新博客,今天休息顺便把golangwebsocket研究了一下,挺好玩的,写了一个聊天室,分享给大家.
websocket包:code.google.com/p/go.net/websocket
文档:http://go.pkgdoc.org/code.google.com/p/go.net/websocket
首先安装websocket包
gogetcode.google.com/p/go.net/websocket
下来就是聊天室代码了,呵呵
golangwebsocket聊天室
packagemain import( "fmt" "io" "bufio" "net/http" "code.google.com/p/go.net/websocket" "container/list" ) varconnidint varconns*list.List funcChatroomServer(ws*websocket.Conn){ deferws.Close() connid++ id:=connid fmt.Printf("connectionid:%d\n",id) item:=conns.PushBack(ws) deferconns.Remove(item) name:=fmt.Sprintf("user%d",id) SendMessage(nil,fmt.Sprintf("welcome%sjoin\n",name)) r:=bufio.NewReader(ws) for{ data,err:=r.ReadBytes('\n') iferr!=nil{ fmt.Printf("disconnectedid:%d\n",id) SendMessage(item,fmt.Sprintf("%soffline\n",name)) break } fmt.Printf("%s:%s",name,data) SendMessage(item,fmt.Sprintf("%s\t>%s",name,data)) } } funcSendMessage(self*list.Element,datastring){ //for_,item:=rangeconns{ foritem:=conns.Front();item!=nil;item=item.Next(){ ws,ok:=item.Value.(*websocket.Conn) if!ok{ panic("itemnot*websocket.Conn") } ifitem==self{ continue } io.WriteString(ws,data) } } //网页客户端 funcClient(whttp.ResponseWriter,r*http.Request){ html:=`<!doctypehtml> <html> <head> <metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/> <title>golangwebsocketchatroom</title> <scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script> varws=newWebSocket("ws://127.0.0.1:6611/chatroom"); ws.onopen=function(e){ console.log("onopen"); console.dir(e); }; ws.onmessage=function(e){ console.log("onmessage"); console.dir(e); $('#log').append('<p>'+e.data+'<p>'); $('#log').get(0).scrollTop=$('#log').get(0).scrollHeight; }; ws.onclose=function(e){ console.log("onclose"); console.dir(e); }; ws.onerror=function(e){ console.log("onerror"); console.dir(e); }; $(function(){ $('#msgform').submit(function(){ ws.send($('#msg').val()+"\n"); $('#log').append('<pstyle="color:red;">My>'+$('#msg').val()+'<p>'); $('#log').get(0).scrollTop=$('#log').get(0).scrollHeight; $('#msg').val(''); returnfalse; }); }); </script> </head> <body> <divid="log"style="height:300px;overflow-y:scroll;border:1pxsolid#CCC;"> </div> <div> <formid="msgform"> <inputtype="text"id="msg"size="60"/> </form> </div> </body> </html>` io.WriteString(w,html) } funcmain(){ fmt.Printf(`Welcomechatroomserver! author:dotcoozhao 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); iferr!=nil{ panic("ListenAndServe:"+err.Error()) } }
简陋了些,但是基本功能都有了.
golangwebsocket客户端
packagemain import( "fmt" "bufio" "io" "os" "code.google.com/p/go.net/websocket" ) funcCommand(ws*websocket.Conn){ r:=bufio.NewReader(os.Stdin) w:=bufio.NewWriter(ws) for{ data,err:=r.ReadBytes('\n') iferr!=nil{ panic(err) } _,err=w.Write(data) iferr!=nil{ panic(err) } w.Flush() fmt.Printf("My\t>") } } funcmain(){ fmt.Printf(`Welcomechatroom! author:dotcoozhao url:http://www.dotcoo.com/golang-websocket-chatroom `) origin:="http://127.0.0.1:6611/" url:="ws://127.0.0.1:6611/chatroom" ws,err:=websocket.Dial(url,"",origin) iferr!=nil{ panic(err) } deferws.Close() r:=bufio.NewReader(ws) //w:=bufio.NewWriter(os.Stdout) goCommand(ws) for{ data,err:=r.ReadBytes('\n') iferr==io.EOF{ fmt.Printf("disconnected\n") os.Exit(0) } iferr!=nil{ panic(err) } fmt.Printf("\r%sMy\t>",data) } }
希望本文所述对大家Go语言程序设计有所帮助。