http://www.cnblogs.com/wangrudong003/p/5535689.htmlgo代码部分:
1// WebChat project main.go
2package main
3
4import (
5 "fmt"
6 "net/http"
7 "time"
8
9 "encoding/json"
10
11 "strings"
12
13 "golang.org/x/net/websocket"
14)
15
16//全局信息
17var datas Datas
18var users map[*websocket.Conn]string
19
20func main() {
21 fmt.Println("启动时间")
22 fmt.Println(time.Now())
23
24 //初始化
25 datas = Datas{}
26 users = make(map[*websocket.Conn]string)
27
28 //绑定效果页面
29 http.HandleFunc("/", h_index)
30 //绑定socket方法
31 http.Handle("/webSocket", websocket.Handler(h_webSocket))
32 //开始监听
33 http.ListenAndServe(":8", nil)
34}
35
36func h_index(w http.ResponseWriter, r *http.Request) {
37
38 http.ServeFile(w, r, "index.html")
39}
40
41func h_webSocket(ws *websocket.Conn) {
42
43 var userMsg UserMsg
44 var data string
45 for {
46
47 //判断是否重复连接
48 if _, ok := users[ws]; !ok {
49 users[ws] = "匿名"
50 }
51 userMsgsLen := len(datas.UserMsgs)
52 fmt.Println("UserMsgs", userMsgsLen, "users长度:", len(users))
53
54 //有消息时,全部分发送数据
55 if userMsgsLen > 0 {
56 b, errMarshl := json.Marshal(datas)
57 if errMarshl != nil {
58 fmt.Println("全局消息内容异常")
59 break
60 }
61 for key, _ := range users {
62 errMarshl = websocket.Message.Send(key, string(b))
63 if errMarshl != nil {
64 //移除出错的链接
65 delete(users, key)
66 fmt.Println("发送出错")
67 break
68 }
69 }
70 datas.UserMsgs = make([]UserMsg, 0)
71 }
72
73 fmt.Println("开始解析数据")
74 err := websocket.Message.Receive(ws, &data)
75 fmt.Println("data:", data)
76 if err != nil {
77 //移除出错的链接
78 delete(users, ws)
79 fmt.Println("接收出错")
80 break
81 }
82
83 data = strings.Replace(data, "\n", "", 0)
84 err = json.Unmarshal([]byte(data), &userMsg)
85 if err != nil {
86 fmt.Println("解析数据异常")
87 break
88 }
89 fmt.Println("请求数据类型:", userMsg.DataType)
90
91 switch userMsg.DataType {
92 case "send":
93 //赋值对应的昵称到ws
94 if _, ok := users[ws]; ok {
95 users[ws] = userMsg.UserName
96
97 //清除连接人昵称信息
98 datas.UserDatas = make([]UserData, 0)
99 //重新加载当前在线连接人
100 for _, item := range users {
101
102 userData := UserData{UserName: item}
103 datas.UserDatas = append(datas.UserDatas, userData)
104 }
105 }
106 datas.UserMsgs = append(datas.UserMsgs, userMsg)
107 }
108 }
109
110}
111
112type UserMsg struct {
113 UserName string
114 Msg string
115 DataType string
116}
117
118type UserData struct {
119 UserName string
120}
121
122type Datas struct {
123 UserMsgs []UserMsg
124 UserDatas []UserData
125} html5代码:
<!DOCTYPE html>
<html lang="zh-CN">
<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 class="container">
<div>内容:</div>
<div class="list-group" 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 class="list-group" id="divUsers">
在线:<br />
<!--<div class="btn btn-default">111</div>-->
</div>
<div>
昵称:<input class="form-control" id="txtUserName" value="红领巾" type="text" maxlength="20" style="width: 30%; margin-bottom: 15px" />
聊聊:<textarea class="form-control" id="txtContent" autofocus rows="6" placeholder="想聊的内容" maxlength="200" required style="width: 60%; "></textarea>
<button class="btn btn-default" id="btnSend" style="margin-top:15px">发 送</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("请输入发送内容!"); 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>
效果图:
附件:http://www.cppblog.com/Files/kenkao/GoWebsocket.zip
posted on 2016-09-07 17:56
思月行云 阅读(1285)
评论(0) 编辑 收藏 引用 所属分类:
Golang