聊天功能基本完成

This commit is contained in:
junleea 2024-08-08 18:04:45 +08:00
parent ba268f1422
commit 1c9a259ca2
2 changed files with 136 additions and 25 deletions

View File

@ -1,6 +1,11 @@
<template>
<el-container class="layout-container-demo" style="height: 700px;width: 1000px;">
<el-aside width="200px">
<el-input
placeholder="请输入用户姓名"
v-model="searchName"
@input="filterUsers"
></el-input>
<el-scrollbar>
<el-menu :default-openeds="['1', '3']">
<el-sub-menu index="1">
@ -10,9 +15,9 @@
</el-icon>
</template>
<el-scrollbar height="300px">
<el-menu-item-group v-for="user in userList" :key="user.id">
<el-menu-item-group v-for="user in filteredUsers" :key="user.id">
<el-menu-item :index="String(user.id)" @click="handleGetMessage(user.id)" style="height: 40px;">
{{ user.email }}
{{ user.name }}
</el-menu-item>
</el-menu-item-group>
</el-scrollbar>
@ -39,19 +44,14 @@
<el-container width="800px">
<el-header style="text-align: right; font-size: 12px">
<div class="toolbar">
<el-text class="mx-1" type="primary" style="margin-right: 10px;">{{ message }}</el-text>
<!-- 重新连接websocket按钮 -->
<ElButton type="primary" style="margin-right: 10px;" @click="reconnect()">重新连接</ElButton>
<el-button
type="primary"
size="mini"
@click.prevent="handleMenuSelect('/videoList')"
>返回</el-button
>
<el-text class="mx-1" type="primary" >目前:{{ cur_user_name }}</el-text>
<el-dropdown>
<el-icon style="margin-right: 10px; margin-top: 1px" size="25px">
<setting />
</el-icon>
</el-dropdown>
<span @click="updateUser()" style=" margin-left: 30px; color: #12B7F5; text-decoration: underline; cursor: pointer;
">修改用户名</span>
<input type="text" v-if="isUpdate" v-model="newUserName" />
<span v-if="isUpdate" @click="makeSure">确定</span>
<div>
<span style=" margin-right: 10px;margin-left: 10px;">{{ username }}</span>
<el-avatar size="default" fit="fit"> {{ username }} </el-avatar>
@ -80,7 +80,7 @@
<div v-if="uid == item.FromUserID && item.ToUserID == cur_user_id" style="margin-right: 10px;margin-bottom: 8px;">
<el-row class="row-bg" type="flex" justify="end" align="middle">
<span style="margin-right: 10px">{{ formatTime(item.CreatedAt)}}</span>
<el-avatar size="default" fit="fit"> {{ item.username }} </el-avatar>
<el-avatar size="default" fit="fit"> {{ tokenData.username }} </el-avatar>
</el-row>
<el-row justify="end">
@ -131,8 +131,11 @@ export default {
},
username: localStorage.getItem("username"),
userList: [],
filteredUsers: [], //
to_user_id:0,
cur_user_id:0,
searchName: '', //
cur_user_name: "",
eventSource: null, //
uid: localStorage.getItem("userId"),
@ -156,11 +159,22 @@ export default {
this.userList=data.friends;
this.groupList=data.groups;
},
filterUsers() {
this.filteredUsers = this.userList.filter(user => {
return user.name.toLowerCase().includes(this.searchName.toLowerCase());
});
},
async handleGetMessage(id){
let result = {};
this.to_user_id=id;
this.cur_user_id=id;
console.log("uid:",this.uid,"\tcur_user_id:",this.cur_user_id)
for(let i=0; i<this.userList.length; i++){
if(this.userList[i].id === id){
this.cur_user_name=this.userList[i].name;
break;
}
}
try {
let req={
token: localStorage.getItem("token"),
@ -199,18 +213,86 @@ export default {
},
formatTime(time){
let date = new Date(time);
let year = date.getFullYear();
let month = date.getMonth() + 1;
let day = date.getDate();
let hour = date.getHours();
let minute = date.getMinutes();
let second = date.getSeconds();
return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
//
const year = date.getFullYear();
const month = ('0' + (date.getMonth() + 1)).slice(-2); // 01
const day = ('0' + date.getDate()).slice(-2);
const hour = ('0' + date.getHours()).slice(-2);
const minute = ('0' + date.getMinutes()).slice(-2);
const second = ('0' + date.getSeconds()).slice(-2);
//
return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
},
connectSSE(){
connectWebSocket() {
// WebSocket
let _this = this;
if (typeof WebSocket == "undefined") {
console.log("浏览器不支持WebSocket");
} else {
console.log("浏览器支持WebSocket");
let socketUrl =
"wss://gep.ljsea.xyz/im/ws_v2?to_user_id=" +
this.to_user_id +
"&token=" +
this.tokenData.token;
// console.log("socketUrl:", socketUrl);
if (this.socket != null) {
this.socket.close();
this.socket = null;
}
// websocket
this.socket = new WebSocket(socketUrl);
//
this.socket.onopen = function () {
this.loading=false
//alert("");
ElMessage({
message: "连接成功",
type: "success",
})
};
this.socket.onerror = (error) => {
console.error("WebSocket Error:", error);
};
//
this.socket.onclose = function () {
//alert("!");
ElMessage({
message: "连接已关闭",
type: "error",
})
router.push("/user");
};
//
this.socket.onmessage = async function (msg) {
//console.log("====" + msg.data);
let data = JSON.parse(msg.data); // json
// console.log("====" + data);
// json
console.log("data.type:", data.type);
if (data.type == "msg") { //
// console.log("====" + JSON.stringify(msg.data));
console.log("msg_:", data.data);
_this.MsgList.push(JSON.parse(data.data));
//console.log("msglist:", _this.MsgList);
//
}else if (data.type == "check") {
//alert("线");
console.log(data.type)
}
};
}
},
async connectSSE(){
if (!!window.EventSource) {
this.eventSource = new EventSource("https://gep.ljsea.xyz/im/sse_msg?token="+this.tokenData.token);
let this_=this
this.eventSource.onopen = function(event) {
console.log("连接已建立!");
};
this.eventSource.onmessage = function(event) {
console.log(event.data);
let msg = JSON.parse(event.data);
@ -220,12 +302,16 @@ export default {
}
};
this.eventSource.onerror = (error) => {
//
this.connectSSE();
if (this.eventSource.readyState === EventSource.CLOSED) {
//console.log('Connection was closed by the server.');
ElMessage({
message: "连接已关闭!",
message: "连接已关闭!:"+error,
type: "error",
})
// Optionally, try to reconnect
} else {
//console.error('EventSource failed:', error);
@ -252,6 +338,10 @@ export default {
});
},
async handleSendBtnClick(){
if(this.currentMsg =="" || this.currentMsg === null){
ElMessage.error("消息不能为空!");
return
}
let result = {};
try {
let req={
@ -323,9 +413,16 @@ export default {
// console.log("mounted");
await this.getIpClient();
await this.handleSelectUser();
//this.connectSSE();
this.filteredUsers=this.userList;
//await this.connectSSE();
this.connectWebSocket();
this.handleGetMessage(this.userList[0].id);
},
onUnmounted() {
if (this.eventSource) {
this.eventSource.close();
}
},
};
</script>

View File

@ -27,6 +27,9 @@ export default {
async getUserList() {
let result = {};
try {
if(this.search_id === "" || this.search_id === null){
this.search_id = -1;
}
this.tokenData.id = this.search_id;
this.tokenData.keyword = this.keyword;
Cookies.set("search_id", this.search_id);
@ -38,6 +41,10 @@ export default {
let data = result.data;
this.tableData = data;
},
requestFriend(index) {
var id = this.tableData[index].ID;
var name = this.tableData[index].Name;
},
onSubmit() {
getUserList({ token: token });
},
@ -195,6 +202,13 @@ export default {
@click.prevent="startChat(scope.$index)"
>聊天</el-button
>
<el-button
type="primary"
size="mini"
@click.prevent="requestFriend(scope.$index)"
>请求加好友</el-button
>
<!-- <el-button type="danger" size="mini">删除</el-button> -->
</template>
</el-table-column>