11.3 gin websocket 一对一聊天

依赖包

  1. github.com/gin-gonic/gin
  2. github.com/gorilla/websocket

代码

创建ws/ws.go

  1. package ws
  2. import (
  3. "encoding/json"
  4. "github.com/gin-gonic/gin"
  5. "github.com/gorilla/websocket"
  6. "log"
  7. "net/http"
  8. )
  9. // ClientManager is a websocket manager
  10. type ClientManager struct {
  11. Clients map[string]*Client
  12. Broadcast chan []byte
  13. Register chan *Client
  14. Unregister chan *Client
  15. }
  16. // Client is a websocket client
  17. type Client struct {
  18. ID string
  19. Socket *websocket.Conn
  20. Send chan []byte
  21. }
  22. // Message is return msg
  23. type Message struct {
  24. Sender string `json:"sender,omitempty"`
  25. Recipient string `json:"recipient,omitempty"`
  26. Content string `json:"content,omitempty"`
  27. }
  28. // Manager define a ws server manager
  29. var Manager = ClientManager{
  30. Broadcast: make(chan []byte),
  31. Register: make(chan *Client),
  32. Unregister: make(chan *Client),
  33. Clients: make(map[string]*Client),
  34. }
  35. // Start is 项目运行前, 协程开启start -> go Manager.Start()
  36. func (manager *ClientManager) Start() {
  37. for {
  38. log.Println("<---管道通信--->")
  39. select {
  40. case conn := <-Manager.Register:
  41. log.Printf("新用户加入:%v", conn.ID)
  42. Manager.Clients[conn.ID] = conn
  43. jsonMessage, _ := json.Marshal(&Message{Content: "Successful connection to socket service"})
  44. conn.Send <- jsonMessage
  45. case conn := <-Manager.Unregister:
  46. log.Printf("用户离开:%v", conn.ID)
  47. if _, ok := Manager.Clients[conn.ID]; ok {
  48. jsonMessage, _ := json.Marshal(&Message{Content: "A socket has disconnected"})
  49. conn.Send <- jsonMessage
  50. close(conn.Send)
  51. delete(Manager.Clients, conn.ID)
  52. }
  53. case message := <-Manager.Broadcast:
  54. MessageStruct :=Message{}
  55. json.Unmarshal(message, &MessageStruct)
  56. for id, conn := range Manager.Clients {
  57. if id!=creatId(MessageStruct.Recipient,MessageStruct.Sender){
  58. continue
  59. }
  60. select {
  61. case conn.Send <- message:
  62. default:
  63. close(conn.Send)
  64. delete(Manager.Clients, conn.ID)
  65. }
  66. }
  67. }
  68. }
  69. }
  70. func creatId(uid,touid string) string {
  71. return uid+"_"+touid
  72. }
  73. func (c *Client) Read() {
  74. defer func() {
  75. Manager.Unregister <- c
  76. c.Socket.Close()
  77. }()
  78. for {
  79. c.Socket.PongHandler()
  80. _, message, err := c.Socket.ReadMessage()
  81. if err != nil {
  82. Manager.Unregister <- c
  83. c.Socket.Close()
  84. break
  85. }
  86. log.Printf("读取到客户端的信息:%s", string(message))
  87. Manager.Broadcast <- message
  88. }
  89. }
  90. func (c *Client) Write() {
  91. defer func() {
  92. c.Socket.Close()
  93. }()
  94. for {
  95. select {
  96. case message, ok := <-c.Send:
  97. if !ok {
  98. c.Socket.WriteMessage(websocket.CloseMessage, []byte{})
  99. return
  100. }
  101. log.Printf("发送到到客户端的信息:%s", string(message))
  102. c.Socket.WriteMessage(websocket.TextMessage, message)
  103. }
  104. }
  105. }
  106. //TestHandler socket 连接 中间件 作用:升级协议,用户验证,自定义信息等
  107. func WsHandler(c *gin.Context) {
  108. uid := c.Query("uid")
  109. touid := c.Query("to_uid")
  110. conn, err := (&websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }}).Upgrade(c.Writer, c.Request, nil)
  111. if err != nil {
  112. http.NotFound(c.Writer, c.Request)
  113. return
  114. }
  115. //可以添加用户信息验证
  116. client := &Client{
  117. ID: creatId(uid,touid),
  118. Socket: conn,
  119. Send: make(chan []byte),
  120. }
  121. Manager.Register <- client
  122. go client.Read()
  123. go client.Write()
  124. }

创建main.go

  1. package main
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "im/ws"
  5. )
  6. //server
  7. func main() {
  8. gin.SetMode(gin.ReleaseMode) //线上环境
  9. go ws.Manager.Start()
  10. r := gin.Default()
  11. r.GET("/ws",ws.WsHandler)
  12. r.GET("/pong", func(c *gin.Context) {
  13. c.JSON(200, gin.H{
  14. "message": "pong",
  15. })
  16. })
  17. r.Run(":8282") // listen and serve on 0.0.0.0:8080
  18. }

运行服务端

  1. go run mian.go

创建client.html

  1. <html>
  2. <head>
  3. <title>Golang Chat</title>
  4. <script src="http://libs.baidu.com/jquery/1.4.2/jquery.min.js"></script>
  5. <meta charset="UTF-8" />
  6. <script type="text/javascript">
  7. $(function() {
  8. function getUrlParam(name)
  9. {
  10. var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
  11. var r = window.location.search.substr(1).match(reg); //匹配目标参数
  12. if (r!=null) return unescape(r[2]); return null; //返回参数值
  13. }
  14. var conn;
  15. var msg = $("#msg");
  16. var log = $("#log");
  17. uid=getUrlParam("uid");
  18. to_uid=getUrlParam("to_uid");
  19. function appendLog(msg) {
  20. var d = log[0]
  21. var doScroll = d.scrollTop == d.scrollHeight - d.clientHeight;
  22. msg.appendTo(log)
  23. if (doScroll) {
  24. d.scrollTop = d.scrollHeight - d.clientHeight;
  25. }
  26. }
  27. $("#form").submit(function() {
  28. if (!conn) {
  29. return false;
  30. }
  31. if (!msg.val()) {
  32. return false;
  33. }
  34. var json = {"sender":uid,"recipient":to_uid,"content":msg.val()}; //创建对象;
  35. var jsonStr = JSON.stringify(json); //转为JSON字符串
  36. conn.send(jsonStr);
  37. msg.val("");
  38. return false
  39. });
  40. if (window["WebSocket"]) {
  41. conn = new WebSocket("ws://localhost:8282/ws?uid="+uid+"&to_uid="+to_uid);
  42. conn.onclose = function(evt) {
  43. appendLog($("<div><b>Connection Closed.</b></div>"))
  44. }
  45. conn.onmessage = function(evt) {
  46. appendLog($("<div/>").text(evt.data))
  47. }
  48. } else {
  49. appendLog($("<div><b>WebSockets Not Support.</b></div>"))
  50. }
  51. });
  52. </script>
  53. <style type="text/css">
  54. html {
  55. overflow: hidden;
  56. }
  57. body {
  58. overflow: hidden;
  59. padding: 0;
  60. margin: 0;
  61. width: 100%;
  62. height: 100%;
  63. background: gray;
  64. }
  65. #log {
  66. background: white;
  67. margin: 0;
  68. padding: 0.5em 0.5em 0.5em 0.5em;
  69. position: absolute;
  70. top: 0.5em;
  71. left: 0.5em;
  72. right: 0.5em;
  73. bottom: 3em;
  74. overflow: auto;
  75. }
  76. #form {
  77. padding: 0 0.5em 0 0.5em;
  78. margin: 0;
  79. position: absolute;
  80. bottom: 1em;
  81. left: 0px;
  82. width: 100%;
  83. overflow: hidden;
  84. }
  85. </style>
  86. </head>
  87. <body>
  88. <div id="log"></div>
  89. <form id="form">
  90. <input type="submit" value="发送" />
  91. <input type="text" id="msg" size="64"/>
  92. </form>
  93. </body>
  94. </html>

自己搭建nginx或apache等web服务,分别在两个窗口运行

http://localhost/client.html?uid=1&to_uid=2

http://localhost/client.html?uid=2&to_uid=1

这样就可以聊天了

links

  • 目录
  • 上一节:
  • 下一节: