[Golang] Simple chat room implementation

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. Recently wrote a chrome websocket extension, server End with Java Netty Framework, later found Golang implementation websocket very simple, efficient, the following is an example, simple implementation of user login, broadcast, equivalent to chat room!


[Plain]View Plaincopyprint?
  1. Package Main
  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"//server address
  13. )
  14. VAR (
  15. PWD, _ = os. GETWD ()
  16. Roottemp = template. Must (template. Parsefiles (pwd + "/chat.html"))
  17. JSON = WebSocket. JSON//Codec for JSON
  18. Message = WebSocket. Message//codec for string, []byte
  19. Activeclients = Make (map[clientconn]string)//Map containing clients
  20. User = Make (map[string]string)
  21. )
  22. Initialize handlers and WebSocket handlers
  23. Func init () {
  24. User["AAA"] = "AAA"
  25. user["BBB"] = "BBB"
  26. user["test"] = "Test"
  27. user["test2"] = "test2"
  28. user["test3"] = "test3"
  29. }
  30. Client connection consists of the WebSocket and the client IP
  31. Type Clientconn struct {
  32. WebSocket *websocket. Conn
  33. ClientIP string
  34. }
  35. WebSocket server to handle chat between clients
  36. Func sockserver (ws *websocket. Conn) {
  37. var err error
  38. var clientmessage string
  39. Use []byte if WebSocket binary type is blob or Arraybuffer
  40. var clientmessage []byte
  41. Cleanup on server side
  42. Defer func () {
  43. If Err = ws. Close (); Err! = Nil {
  44. Log. Println ("Websocket could not be closed", err. Error ())
  45. }
  46. }()
  47. Client: = ws. Request (). Remoteaddr
  48. Log. PRINTLN ("Client connected:", client)
  49. SOCKCLI: = clientconn{ws, client}
  50. ACTIVECLIENTS[SOCKCLI] = ""
  51. Log. Println ("Number of clients connected:", Len (activeclients))
  52. For loop so the websocket stays open otherwise
  53. It ' ll close after one receieve and Send
  54. for {
  55. If Err = message.receive (WS, &clientmessage); Err! = Nil {
  56. If We cannot Read then the connection is closed
  57. Log. Println ("Websocket disconnected Waiting", err. Error ())
  58. Remove the WS client conn from our active clients
  59. Delete (activeclients, SOCKCLI)
  60. Log. Println ("Number of clients still connected:", Len (activeclients))
  61. Return
  62. }
  63. var Msg_arr = strings. Split (clientmessage, "|")
  64. If msg_arr[0] = = "Login" && len (msg_arr) = = 3 {
  65. Name: = Msg_arr[1]
  66. Pass: = Msg_arr[2]
  67. If pass = = User[name] {
  68. ACTIVECLIENTS[SOCKCLI] = Name
  69. If Err = Message.send (WS, "login|" +name); Err! = Nil {
  70. Log. Println ("Could not send Message to", client, err.) Error ())
  71. }
  72. } else {
  73. Log. PRINTLN ("Login faild:", Clientmessage)
  74. }
  75. } else if msg_arr[0] = = "MSG" {
  76. If ACTIVECLIENTS[SOCKCLI]! = "" {
  77. Clientmessage = "Msg|" + time. Now (). Format ("2006-01-02 15:04:05") + "" + ACTIVECLIENTS[SOCKCLI] + "said:" + msg_arr[1]
  78. For cs, na: = Range activeclients {
  79. If na! = "" {
  80. If Err = Message.send (Cs.websocket, clientmessage); Err! = Nil {
  81. Log. Println ("Could not send Message to", Cs.clientip, err.) Error ())
  82. }
  83. }
  84. }
  85. }
  86. }
  87. }
  88. }
  89. Roothandler renders the template for the root page
  90. Func Roothandler (w http. Responsewriter, req *http. Request) {
  91. ERR: = Roottemp.execute (W, LISTENADDR)
  92. If err! = Nil {
  93. http. Error (W, err. Error (), HTTP. Statusinternalservererror)
  94. }
  95. }
  96. Func Main () {
  97. http. Handlefunc ("/", Roothandler)
  98. http. Handle ("/socket", WebSocket. Handler (Sockserver))
  99. ERR: = http. Listenandserve (listenaddr, nil)
  100. If err! = Nil {
  101. Panic ("Listenandserve:" + Err. Error ())
  102. }
  103. }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.