<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                > ### 第四例 聊天室 * 客戶端 ~~~ <!DOCTYPE HTML> <html > <head > <meta charset="utf-8" > <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js" ></script > </head > <body > <form > <div id="div1" ></div > <hr > <textarea style="width: 300px;height: 100px;" id="content" ></textarea > <input type="button" value="發送" onclick="Send()" > </form > </body > <script > function GetQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if (r != null) return unescape(r[2]); return null; } //?roomId=1&userId=1000&userName=winnie&connType=1 var roomId = GetQueryString("roomId"); var userId = GetQueryString("userId"); var userName = GetQueryString("userName"); var connType = GetQueryString("connType"); var wsCopy; //服務端地址 //var wsUrl = "ws://127.0.0.1:8095/message?roomId=22&userId=222&userName=王五&connType=2"; var wsUrl = "ws://127.0.0.1:8095/message?roomId=" + roomId + "&userId=" + userId + "&userName=" + userName + "&connType=" + connType; //心跳檢測 var heartTimeOut = 10 * 1000; //10s (1000 毫秒= 1 秒) - 設置時間比nginx超時時間短) //斷線重連 var reConnTimeOut = 2 * 1000; //心跳檢測 var heartCheck = { timer: null, timeout: heartTimeOut, start: function (ws) { this.timer = setInterval(function () { console.log("heartCheck"); ws.send("ping www.51websocket.cn"); }, this.timeout); } }; //斷線重連 var reConnection = { timer: null, timeout: reConnTimeOut, url: wsUrl, start: function (ws) { if (!ws.token) { this.timer = setTimeout(function () { console.log("ReConnect"); createWebSocket(this.url); }, this.timeout); } } }; //創建連接 createWebSocket(wsUrl); function createWebSocket() { try { var ws = new WebSocket(wsUrl); init(ws); } catch (e) { console.log('catch'); reConnection.start(); } } function init(ws) { //TODO : 連接關閉時觸發 ws.onclose = function () { clearInterval(heartCheck.timer); if (this.token == undefined) { //多種錯誤事件, 只會觸發一個斷線重連 this.token = false; } else if (this.token == false) { this.token = true; } console.log('Close'); reConnection.start(this); }; //通信發生錯誤時觸發 ws.onerror = function () { clearInterval(heartCheck.timer); if (this.token == undefined) { this.token = false; } else if (this.token == false) { this.token = true; } console.log('Error'); reConnection.start(this); }; //連接建立時觸發 ws.onopen = function () { clearTimeout(reConnection.timer); console.log('Connect'); //心跳檢測重置 heartCheck.start(this); wsCopy = ws; }; //客戶端接收服務端數據時觸發 ws.onmessage = function (event) { $("#div1").append("<h3>" + event.data + "</h3>"); } } //向服務端發送消息 function Send() { wsCopy.send($("#content").val()); $("#content").val(""); } </script > </html > ~~~ * 服務端 ~~~ package main //如果是服務掛了, 重啟的話, 重數據庫里讀取聊天信息 import ( "chatbox/zdbmodel" "chatbox/zlogs" "golang.org/x/net/websocket" "net/http" "strconv" "fmt" "time" "strings" ) //直播間信息 type LiveRoom struct { user map[int]*UserInfo //直播間用戶 ch chan []byte //發送彈幕 msg [][]byte //歷史彈幕 } //用戶信息 type UserInfo struct { id int //用戶Id name string //用戶名稱 conn *websocket.Conn //當前用戶的連接 connType int //用戶類型 1-游客 2-會員 } //公共函數 func commAtoi(s string) (int) { if n, err := strconv.Atoi(s); err == nil { return n } return 0 } var list map[int]*LiveRoom var roomUser map[int]*UserInfo var roomCh chan []byte var roomMsg [][]byte func svrConnHandler(conn *websocket.Conn) { //TODO : 表單數據處理 r := conn.Request() r.ParseForm() roomId := r.Form["roomId"][0] userId := r.Form["userId"][0] userName := r.Form["userName"][0] connType := r.Form["connType"][0] rId := commAtoi(roomId) uId := commAtoi(userId) cType := commAtoi(connType) //TODO : 構建結構體 uInfo := &UserInfo{ id: uId, name: userName, conn: conn, connType: cType, } _, ok := list[rId] if !ok { roomUser = make(map[int]*UserInfo, 100) roomCh = make(chan []byte, 100) roomMsg = make([][]byte, 100) } roomUser[uId] = uInfo list[rId] = &LiveRoom{ user: roomUser, ch: roomCh, msg: roomMsg, } //TODO : 接收客戶端消息 go func() { var content [1024]byte for { connUserInfo := list[rId].user[uId] n, err := connUserInfo.conn.Read(content[:]) if err != nil { list[rId].user[uId].conn.Close() delete(list[rId].user, uId) break } if n > 0 { if string(content[:n]) == string("ping www.51websocket.cn") { content = [1024]byte{} continue } content2 := append([]byte(fmt.Sprint(userId, ":::", userName, ":::")), content[:n]...) list[rId].ch <- content2 content = [1024]byte{} } } }() //TODO : 向客戶端發送消息 if !ok { for { select { case content := <-list[rId].ch: message := strings.Split(string(content), ":::") list[rId].msg = append(list[rId].msg, []byte("<span class='name'>"+message[1]+":"+"</span>"+message[2])) for _, v := range list[rId].user { v.conn.Write([]byte("<span class='name'>" + message[1] + ":" + "</span>" + message[2])) } } } //<--向客戶端發送消息--> } else { for { time.Sleep(time.Second * 60 * 60) } } } func main() { list = make(map[int]*LiveRoom, 10) zlogs.InitLog() zdbmodel.InitDb() http.Handle("/message", websocket.Handler(svrConnHandler)) err := http.ListenAndServe(":8095", nil) zlogs.ErrorLog(err) } ~~~
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看