[Golang]简单的聊天室实现

前端之家收集整理的这篇文章主要介绍了[Golang]简单的聊天室实现前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

最近写了一个chrome的websocket extension,server端用的是Java的Netty框架,后来发现golang 实现websocket 非常简单,高效, 下面是例子, 简单实现了用户登录,广播,相当于聊天室!


  1. packagemain
  2. import(
  3. "code.google.com/p/go.net/websocket"
  4. "html/template"
  5. "log"
  6. "net/http"
  7. "os"
  8. "strings"
  9. "time"
  10. )
  11. const(
  12. listenAddr="localhost:9527"//serveraddress
  13. )
  14. var(
  15. pwd,_=os.Getwd()
  16. RootTemp=template.Must(template.ParseFiles(pwd+"/chat.html"))
  17. JSON=websocket.JSON//codecforJSON
  18. Message=websocket.Message//codecforstring,[]byte
  19. ActiveClients=make(map[ClientConn]string)//mapcontainingclients
  20. User=make(map[string]string)
  21. )
  22. //Initializehandlersandwebsockethandlers
  23. funcinit(){
  24. User["aaa"]="aaa"
  25. User["bbb"]="bbb"
  26. User["test"]="test"
  27. User["test2"]="test2"
  28. User["test3"]="test3"
  29. }
  30. //Clientconnectionconsistsofthewebsocketandtheclientip
  31. typeClientConnstruct{
  32. websocket*websocket.Conn
  33. clientIPstring
  34. }
  35. //WebSocketservertohandlechatbetweenclients
  36. funcSockServer(ws*websocket.Conn){
  37. varerrerror
  38. varclientMessagestring
  39. //use[]byteifwebsocketbinarytypeisbloborarraybuffer
  40. //varclientMessage[]byte
  41. //cleanuponserverside
  42. deferfunc(){
  43. iferr=ws.Close();err!=nil{
  44. log.Println("Websocketcouldnotbeclosed",err.Error())
  45. }
  46. }()
  47. client:=ws.Request().RemoteAddr
  48. log.Println("Clientconnected:",client)
  49. sockCli:=ClientConn{ws,client}
  50. ActiveClients[sockCli]=""
  51. log.Println("Numberofclientsconnected:",len(ActiveClients))
  52. //forloopsothewebsocketstaysopenotherwise
  53. //it'llcloseafteroneReceieveandSend
  54. for{
  55. iferr=Message.Receive(ws,&clientMessage);err!=nil{
  56. //IfwecannotReadthentheconnectionisclosed
  57. log.Println("WebsocketDisconnectedwaiting",err.Error())
  58. //removethewsclientconnfromouractiveclients
  59. delete(ActiveClients,sockCli)
  60. log.Println("Numberofclientsstillconnected:",len(ActiveClients))
  61. return
  62. }
  63. varmsg_arr=strings.Split(clientMessage,"|")
  64. ifmsg_arr[0]=="login"&&len(msg_arr)==3{
  65. name:=msg_arr[1]
  66. pass:=msg_arr[2]
  67. ifpass==User[name]{
  68. ActiveClients[sockCli]=name
  69. iferr=Message.Send(ws,"login|"+name);err!=nil{
  70. log.Println("Couldnotsendmessageto",client,err.Error())
  71. }
  72. }else{
  73. log.Println("loginfaild:",clientMessage)
  74. }
  75. }elseifmsg_arr[0]=="msg"{
  76. ifActiveClients[sockCli]!=""{
  77. clientMessage="msg|"+time.Now().Format("2006-01-0215:04:05")+""+ActiveClients[sockCli]+"Said:"+msg_arr[1]
  78. forcs,na:=rangeActiveClients{
  79. ifna!=""{
  80. iferr=Message.Send(cs.websocket,clientMessage);err!=nil{
  81. log.Println("Couldnotsendmessageto",cs.clientIP,err.Error())
  82. }
  83. }
  84. }
  85. }
  86. }
  87. }
  88. }
  89. //RootHandlerrendersthetemplatefortherootpage
  90. funcRootHandler(whttp.ResponseWriter,req*http.Request){
  91. err:=RootTemp.Execute(w,listenAddr)
  92. iferr!=nil{
  93. http.Error(w,err.Error(),http.StatusInternalServerError)
  94. }
  95. }
  96. funcmain(){
  97. http.HandleFunc("/",RootHandler)
  98. http.Handle("/socket",websocket.Handler(SockServer))
  99. err:=http.ListenAndServe(listenAddr,nil)
  100. iferr!=nil{
  101. panic("ListenAndServe:"+err.Error())
  102. }
  103. }
原文链接:https://www.f2er.com/go/190543.html

猜你在找的Go相关文章