您好,登錄后才能下訂單哦!
這篇文章主要介紹html5怎么使用go+websocket搭建websocket服務,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
這次的就直接發(fā)放代碼截圖吧,應該是用go語言做后臺一個簡易的聊天,這里沒用到什么特別的知識,最樸實的來實現(xiàn)效果,主要目的是分享下h6怎么用websocket,go搭建websocket服務的主要部分。
go代碼部分:
// WebChat project main.go package main import ( "fmt" "net/http" "time" "encoding/json" "strings" "golang.org/x/net/websocket" ) //全局信息 var datas Datas var users map[*websocket.Conn]string func main() { fmt.Println("啟動時間") fmt.Println(time.Now()) //初始化 datas = Datas{} users = make(map[*websocket.Conn]string) //綁定效果頁面 http.HandleFunc("/", h_index) //綁定socket方法 http.Handle("/webSocket", websocket.Handler(h_webSocket)) //開始監(jiān)聽 http.ListenAndServe(":8", nil) } func h_index(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "index.html") } func h_webSocket(ws *websocket.Conn) { var userMsg UserMsg var data string for { //判斷是否重復連接 if _, ok := users[ws]; !ok { users[ws] = "匿名" } userMsgsLen := len(datas.UserMsgs) fmt.Println("UserMsgs", userMsgsLen, "users長度:", len(users)) //有消息時,全部分發(fā)送數(shù)據(jù) if userMsgsLen > 0 { b, errMarshl := json.Marshal(datas) if errMarshl != nil { fmt.Println("全局消息內容異常...") break } for key, _ := range users { errMarshl = websocket.Message.Send(key, string(b)) if errMarshl != nil { //移除出錯的鏈接 delete(users, key) fmt.Println("發(fā)送出錯...") break } } datas.UserMsgs = make([]UserMsg, 0) } fmt.Println("開始解析數(shù)據(jù)...") err := websocket.Message.Receive(ws, &data) fmt.Println("data:", data) if err != nil { //移除出錯的鏈接 delete(users, ws) fmt.Println("接收出錯...") break } data = strings.Replace(data, "\n", "", 0) err = json.Unmarshal([]byte(data), &userMsg) if err != nil { fmt.Println("解析數(shù)據(jù)異常...") break } fmt.Println("請求數(shù)據(jù)類型:", userMsg.DataType) switch userMsg.DataType { case "send": //賦值對應的昵稱到ws if _, ok := users[ws]; ok { users[ws] = userMsg.UserName //清除連接人昵稱信息 datas.UserDatas = make([]UserData, 0) //重新加載當前在線連接人 for _, item := range users { userData := UserData{UserName: item} datas.UserDatas = append(datas.UserDatas, userData) } } datas.UserMsgs = append(datas.UserMsgs, userMsg) } } } type UserMsg struct { UserName string Msg string DataType string } type UserData struct { UserName string } type Datas struct { UserMsgs []UserMsg UserDatas []UserData }
html代碼部分:
<!DOCTYPE html> <html> <head> <title></title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <!-- 新 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css"> <script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script> <!-- <script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>--> </head> <body> <div> <div>內容:</div> <div id="divShow"> <!--<div class="list-group-item list-group-item-success">1111</div> <div class="list-group-item list-group-item-info">1111</div> <div class="list-group-item list-group-item-warning">1111</div> <div class="list-group-item list-group-item-danger">1111</div>--> </div> <div id="divUsers"> 在線:<br /> <!--<div class="btn btn-default">111</div>--> </div> <div> 昵稱:<input id="txtUserName" value="紅領巾" type="text" maxlength="20" style="width: 30%; margin-bottom: 15px" /> 聊聊:<textarea id="txtContent" autofocus rows="6" placeholder="想聊的內容" maxlength="200" required style="width: 60%; "></textarea> <button class="btn btn-default" id="btnSend" style="margin-top:15px">發(fā) 送</button> </div> </div> </body> </html> <script> var tool = function () { var paperLoopNum = 0; var paperTempleArr = [ '<div class="list-group-item list-group-item-success">{0}</div>', '<div class="list-group-item list-group-item-info">{0}</div>', '<div class="list-group-item list-group-item-warning">{0}</div>', '<div class="list-group-item list-group-item-danger">{0}</div>' ]; return { paperDiv: function (val) { var hl = paperTempleArr[paperLoopNum]; paperLoopNum++; if (paperLoopNum >= paperTempleArr.length) { paperLoopNum = 0; } return this.formart(hl, [val]) }, formart: function (str, arrVal) { for (var i = 0; i < arrVal.length; i++) { str = str.replace("{" + i + "}", arrVal[i]); } return str; } } } function showMsg(id, hl, isAppend) { if (!isAppend) { $("#" + id).html(hl); } else { $("#" + id).append(hl); } } $(function () { //初始化工具方法 var tl = new tool(); var wsUrl = "ws://172.16.9.6:8/webSocket"; ws = new WebSocket(wsUrl); try { ws.onopen = function () { //showMsg("divShow", tl.paperDiv("連接服務器-成功")); } ws.onclose = function () { if (ws) { ws.close(); ws = null; } showMsg("divShow", tl.paperDiv("連接服務器-關閉"), true); } ws.onmessage = function (result) { //console.log(result.data); var data = JSON.parse(result.data); $(data.UserMsgs).each(function (i, item) { showMsg("divShow", tl.paperDiv("【" + item.UserName + "】:" + item.Msg), true); }); var userDataShow = []; $(data.UserDatas).each(function (i, item) { userDataShow.push('<div class="btn btn-default">' + item.UserName + '</div>'); }); showMsg("divUsers", userDataShow.join(''), false); } ws.onerror = function () { if (ws) { ws.close(); ws = null; } showMsg("divShow", tl.paperDiv("連接服務器-關閉"), true); } } catch (e) { alert(e.message); } $("#btnSend").on("click", function () { var tContentObj = $("#txtContent"); var tContent = $.trim( tContentObj.val()).replace("/[\n]/g", ""); var tUserName = $.trim( $("#txtUserName").val()); tUserName = tUserName.length <= 0 ? "匿名" : tUserName; if (tContent.length <= 0 || $.trim(tContent).length <= 0) { alert("請輸入發(fā)送內容!"); return; } if (ws == null) { alert("連接失敗,請F5刷新頁面!"); return; } var request = tl.formart('{"UserName": "{0}", "DataType": "{1}", "Msg": "{2}" }', [tUserName, "send", tContent]); ws.send(request); tContentObj.val(""); tContentObj.val($.trim(tContentObj.val()).replace("/[\n]/g", "")); }); $("#txtContent").on("keydown", function (event) { if (event.keyCode == 13) { $("#btnSend").trigger("click"); } }); }) </script>
效果圖:
以上是“html5怎么使用go+websocket搭建websocket服務”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業(yè)資訊頻道!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。