Skip to content

Commit 501ac09

Browse files
committed
fix: 尝试修复消息结构体并发写入问题 #9
1 parent 56f33f8 commit 501ac09

File tree

5 files changed

+59
-26
lines changed

5 files changed

+59
-26
lines changed

readme.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@
66
77
> [github地址](https://github.com/hezhizheng/go-gin-chat)
88
9-
## feature
9+
## Feature
1010
- 登录/注册(防止重复登录)
1111
- 群聊(多房间、支持文字、emoji、文件(图片)上传,使用 [freeimage.host](https://freeimage.host/) 做图床 )
1212
- 私聊(消息提醒)
1313
- 历史消息查看(点击加载更多)
14-
- 心跳检测,来自 https://github.com/zimv/websocket-heartbeat-js
14+
- 心跳检测及自动重连机制,来自 https://github.com/zimv/websocket-heartbeat-js
1515
- go mod 包管理
1616
- 使用 Golang 1.16 embed 内嵌静态资源(html、js、css等),运行只依赖编译好的可执行文件与mysql
1717
- 支持 http/ws 、 https/wss
@@ -244,7 +244,7 @@ gox -osarch="linux/amd64" -ldflags "-s -w" -gcflags="all=-trimpath=${PWD}" -asmf
244244
```
245245

246246

247-
## todo
247+
## TODO
248248
- [x] 心跳机制
249249
- [x] 多频道聊天
250250
- [x] 私聊

static/javascripts/Public.js

+44-13
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,14 @@ function WebSocketConnect(userInfo,toUserInfo = null) {
4444
})
4545

4646
ws.onopen = function () {
47+
// layer.msg("websocket 连接已建立");
48+
chat_info.html(chat_info.html() +
49+
'<li class="systeminfo" > <span>' +
50+
"✅ websocket 连接已建立 " +
51+
'</span></li>');
4752
ws.send(send_data);
4853
//console.log("send_data 发送数据", send_data)
54+
toLow();
4955
};
5056

5157
// if ( toUserInfo )
@@ -68,6 +74,7 @@ function WebSocketConnect(userInfo,toUserInfo = null) {
6874

6975

7076
let chat_info = $('.main .chat_info')
77+
let isServeClose = 0;
7178

7279
ws.onmessage = function (evt) {
7380
var received_msg = JSON.parse(evt.data);
@@ -115,6 +122,7 @@ function WebSocketConnect(userInfo,toUserInfo = null) {
115122
break;
116123
case -1:
117124
ws.close() // 主动close掉
125+
isServeClose = 1
118126
console.log("client 连接已关闭...");
119127
break;
120128
case 4:
@@ -157,23 +165,39 @@ function WebSocketConnect(userInfo,toUserInfo = null) {
157165
default:
158166
}
159167
//console.log("数据已接收...", received_msg);
168+
169+
// 滚动条滚到最下面
170+
toLow();
171+
160172
};
161173

162-
ws.onclose = function () {
174+
ws.onclose = function (evt) {
163175
// 关闭 websocket
164-
chat_info.html(chat_info.html() +
165-
'<li class="systeminfo"> <span>' +
166-
"与服务器连接断开,请刷新页面重试" +
167-
'</span></li>');
176+
if ( isServeClose === 1 ){
177+
chat_info.html(chat_info.html() +
178+
'<li class="systeminfo"> <span>' +
179+
"❌ 与服务器连接断开,请检查是否在浏览器中打开了多个聊天界面" +
180+
'</span></li>');
181+
}else{
182+
chat_info.html(chat_info.html() +
183+
'<li class="systeminfo"> <span>' +
184+
"❌ 与服务器连接断开,正在尝试重新连接,请稍后..." +
185+
'</span></li>');
186+
}
168187
// let c = ws.close() // 主动close掉
169-
console.log("serve 连接已关闭... " + _time());
188+
console.log("serve 连接已关闭... " + _time(),evt);
170189
// console.log(c);
190+
toLow();
171191
};
172192

173193
ws.onerror = function (evt) {
174-
ws.close()
194+
// ws.close()
175195
console.log("触发 onerror",evt)
176196
}
197+
198+
ws.onreconnect = (e) => {
199+
console.log('reconnecting...');
200+
}
177201

178202
} else {
179203
// 浏览器不支持 WebSocket
@@ -184,6 +208,11 @@ function WebSocketConnect(userInfo,toUserInfo = null) {
184208
$(document).ready(function(){
185209
// ------------------------选择聊天室页面-----------------------------------------------
186210

211+
// 在页面即将卸载之前关闭WebSocket连接
212+
window.addEventListener("beforeunload", function() {
213+
console.log("beforeunload close");
214+
ws.close();
215+
});
187216
// 用户信息提交
188217

189218
$('#userinfo_sub').click(function(event) {
@@ -304,9 +333,7 @@ $(document).ready(function(){
304333

305334

306335
// 滚动条滚到最下面
307-
$('.scrollbar-macosx.scroll-content.scroll-scrolly_visible').animate({
308-
scrollTop: $('.scrollbar-macosx.scroll-content.scroll-scrolly_visible').prop('scrollHeight')
309-
}, 500);
336+
toLow();
310337

311338
// 解决input上传文件选择同一文件change事件不生效
312339
event.target.value=''
@@ -357,9 +384,7 @@ $(document).ready(function(){
357384
ws.send(send_data);
358385

359386
// 滚动条滚到最下面
360-
$('.scrollbar-macosx.scroll-content.scroll-scrolly_visible').animate({
361-
scrollTop: $('.scrollbar-macosx.scroll-content.scroll-scrolly_visible').prop('scrollHeight')
362-
}, 500);
387+
toLow();
363388

364389
}
365390

@@ -489,4 +514,10 @@ function isPrivateChat()
489514
return window.location.href.search('private-chat') > 0
490515
}
491516

517+
function toLow() {
518+
$('.scrollbar-macosx.scroll-content.scroll-scrolly_visible').animate({
519+
scrollTop: $('.scrollbar-macosx.scroll-content.scroll-scrolly_visible').prop('scrollHeight')
520+
}, 500);
521+
}
522+
492523

views/private_chat.html

+1-3
Original file line numberDiff line numberDiff line change
@@ -104,9 +104,7 @@
104104
<script>
105105
$(document).ready(function () {
106106
// 滚动到底部
107-
$('.scrollbar-macosx.scroll-content.scroll-scrolly_visible').animate({
108-
scrollTop: $('.scrollbar-macosx.scroll-content.scroll-scrolly_visible').prop('scrollHeight')
109-
}, 500);
107+
toLow();
110108
});
111109
</script>
112110

views/room.html

+1-3
Original file line numberDiff line numberDiff line change
@@ -147,9 +147,7 @@ <h3 class="popover-title">在线用户 1 人</h3>
147147
WebSocketConnect(userInfo)
148148

149149
// 滚动到底部
150-
$('.scrollbar-macosx.scroll-content.scroll-scrolly_visible').animate({
151-
scrollTop: $('.scrollbar-macosx.scroll-content.scroll-scrolly_visible').prop('scrollHeight')
152-
}, 500);
150+
toLow();
153151
});
154152
</script>
155153

ws/go_ws/serve.go

+10-4
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,9 @@ var (
7777
chNotify = make(chan int, 1)
7878

7979
pingMap []interface{}
80+
81+
clientMsgLock = sync.Mutex{}
82+
clientMsgData = clientMsg // 临时存储 clientMsg 数据
8083
)
8184

8285
// 定义消息类型
@@ -199,10 +202,8 @@ func read(c *websocket.Conn, done chan<- struct{}) {
199202
return
200203
}
201204

202-
serveMsgStr := message
203-
204205
// 处理心跳响应 , heartbeat为与客户端约定的值
205-
if string(serveMsgStr) == `heartbeat` {
206+
if string(message) == `heartbeat` {
206207
appendPing(c)
207208
chNotify <- 1
208209
// log.Println("heartbeat pingMap:", pingMap)
@@ -211,7 +212,12 @@ func read(c *websocket.Conn, done chan<- struct{}) {
211212
continue
212213
}
213214

214-
json.Unmarshal(message, &clientMsg)
215+
json.Unmarshal(message, &clientMsgData)
216+
217+
clientMsgLock.Lock()
218+
clientMsg = clientMsgData
219+
clientMsgLock.Unlock()
220+
215221
//fmt.Println("来自客户端的消息", clientMsg, c.RemoteAddr())
216222
if clientMsg.Data.Uid != "" {
217223
if clientMsg.Status == msgTypeOnline { // 进入房间,建立连接

0 commit comments

Comments
 (0)