7. 聊天室(私聊)

需求1.: 私聊需要存储一份聊天记录

2. 用websocket实现长连接进行聊天

3. 私聊,将发送人id和接收人id进行拼接当key存入redis,存入类型 -> list,将聊天记录按照字典的方式存入list

4. 群聊: key值就是群聊名称和创建人id,然后聊天记录无脑存入list即可

5.websocket代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@accept_websocket
def service(request,user_id,uid):
if request.is_websocket():
while 1:
time.sleep(1)
list1 = []
list2 = []
time.sleep(1)
list1.append(uid)
list1.append(user_id)
list1.sort()
key = str(list1)
data = r.lrange(key)
user = User.objects.filter(id=user_id).first()
for j in data:
_ = {}
j = eval(j)
_['uid'] = j['uid']
_['uname'] = user.username
_['name'] = j["name"]
_['jid'] = j["jid"]
_['ch'] = j["ch"]
_['read'] = j["read"]
_['date'] = j['date']
list2.append(_)
list2 = sorted(list2, key=lambda x: x['date'])
request.websocket.send(json.dumps(list2))

6. 添加代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class MessAdd(APIView):
def post(self, request):
uid = request.data.get('uid')
user_id = request.data.get('user_id')
name = request.data.get('name')
list1 = []
list1.append(str(uid))
list1.append(str(user_id))
list1.sort()
key = str(list1)
date = time.time()
info = str({'uid': uid, 'name': name, 'jid': user_id, 'ch': 0, 'read': 0,'date':date})
r.push(key, info)
return Response({'msg': '发送成功'})

7. vue代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<template>
<div>
<div>
<a-button type="primary" @click="showModal">
创建聊天
</a-button>

<div>
<a-modal v-model="visible" title="选择聊天人" @ok="handleOk">
<p v-for="i in userlist" @click="showModal1(i.id)" v-if="uid!=i.id">
{{ i.username }}
</p>
</a-modal>
</div>

<a-modal v-model="visible1" title="聊天" @ok="handleOk1" width="40%">
<a v-for="j in listz">
<p v-if="j.uid == uid" style="text-align: right">{{ j.name }}</p>
<p v-else>{{ j.uname }}发送了: {{ j.name }}</p>
</a>
<a-input id="chat-message-input" v-model="info" type="text"></a-input>
<a-button type="primary" @click="sendmessage">
发送
</a-button>
</a-modal>

</div>
</div>
</template>

<script>
export default {
name: "socket",
data() {
return {
info: '',
listz: [],
visible: false,
userlist: [],
visible1: false,
user_id: '',
uid: localStorage.getItem('id'),
socket:'',
}
},
methods: {
showModal() {
this.visible = true;
},
handleOk(e) {
console.log(e);
this.visible = false;
},
showModal1(id) {
this.visible1 = true;
this.user_id = id
var _this = this
this.socket = new WebSocket(`ws:127.0.0.1:8000/app2/service/${id}/${this.uid}/`)
this.socket.onmessage = function (e) {
_this.listz = JSON.parse(e.data)
};
},
handleOk1(e) {
// console.log(e);
this.socket.close()
this.visible1 = false
this.user_id = ""
this.listz = []
},
sendmessage() {
this.axios({
url: 'http://127.0.0.1:8000/app2/mesadd/',
method: 'post',
data: {'uid': this.uid, 'user_id': this.user_id, 'name': this.info}
}).then(res => {
console.log(res.data)
if(res.data.msg=='发送成功'){
this.info = ""
}
})
},
},
created() {
this.axios({
url: 'http://127.0.0.1:8000/app2/user/'
}).then(res => {
console.log(res.data)
this.userlist = res.data
})
}
}
</script>

<style scoped>

</style>