[Golang]简单的聊天室实现

[Golang]简单的聊天室实现,第1张

概述 最近写了一个chrome的websocket extension, server端用的是Java的Netty框架, 后来发现golang 实现websocket 非常简单,高效, 下面是例子, 简单实现了用户登录,广播,相当于聊天室! [plain] view plain copy print ? package main      import (       "code.google.c  最近写了一个Chrome的websocket extension,server端用的是Java的Netty框架,后来发现golang 实现websocket 非常简单,高效, 下面是例子, 简单实现了用户登录,广播,相当于聊天室!


[plain] view plain copy print ? 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()) } } 总结

以上是内存溢出为你收集整理的[Golang]简单的聊天室实现全部内容,希望文章能够帮你解决[Golang]简单的聊天室实现所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1288477.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-09
下一篇 2022-06-09

发表评论

登录后才能评论

评论列表(0条)

保存