服务器端使用django websocket,客户端使用uniapp 请问服务端和客户端群组互发消息的代码怎么写的参考笔记

2023/8/29 19:21:11

服务器端使用django websocket,客户端使用uniapp 请问服务端和客户端群组互发消息的代码怎么写

2023/8/29 19:22:25

在服务器端使用Django WebSocket和客户端使用Uniapp的情况下,以下是代码示例来实现服务器端和客户端之间的群组互发消息。

服务器端代码(使用Django Channels库):

  1. 首先,在Django的settings.py文件中配置Channels:
 
 

python

# settings.py

INSTALLED_APPS = [
    ...
    'channels',
    ...
]

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels.layers.InMemoryChannelLayer",
    },
}
  1. 创建一个consumers.py文件,并定义WebSocket的消费者类:
 
 

python

# consumers.py

from channels.generic.websocket import WebsocketConsumer

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        # 加入特定群组
        self.room_group_name = 'group_name'
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )
        self.accept()

    def disconnect(self, close_code):
        # 离开群组
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    def receive(self, text_data):
        # 接收到消息后进行处理
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': text_data,
            }
        )

    def chat_message(self, event):
        # 发送消息给群组中的所有成员
        message = event['message']
        self.send(text_data=message)
  1. routing.py文件中配置URL路由:
 
 

python

# routing.py

from django.urls import re_path

from . import consumers

websocket_urlpatterns = [
    re_path(r'ws/chat/$', consumers.ChatConsumer.as_asgi()),
]
  1. 运行Django开发服务器:
 
 

shell

python manage.py runserver

客户端代码(使用Uniapp):

  1. 在uniapp项目中创建一个WebSocket服务文件:
 
 

javascript

// utils/websocket.js

let socketTask = null

export function connectWebSocket() {
  socketTask = uni.connectSocket({
    url: 'ws://your-server-address/ws/chat/', // 替换为您的服务器地址
  })

  socketTask.onOpen(() => {
    console.log('WebSocket连接已打开')
  })

  socketTask.onError(error => {
    console.error('WebSocket连接发生错误', error)
  })

  socketTask.onMessage(message => {
    console.log('收到服务器消息:', message)
    // 处理接收到的消息
  })

  socketTask.onClose(() => {
    console.log('WebSocket连接已关闭')
    // 可在此处进行重连操作
  })
}

export function sendMessage(message) {
  if (socketTask) {
    socketTask.send({
      data: message,
    })
  }
}
  1. 在需要使用WebSocket的页面或组件中引入WebSocket服务文件,并调用函数建立连接和发送消息:
 
 
<template>
  <button @click="sendChatMessage">发送消息</button>
</template>

<script>
import { connectWebSocket, sendMessage } from '@/utils/websocket.js'

export default {
  mounted() {
    connectWebSocket()
  },
  methods: {
    sendChatMessage() {
      sendMessage('Hello, server!') // 发送消息给服务器
    },
  },
}
</script>

以上是使用Django WebSocket和Uniapp实现服务器端和客户端之间群组互发消息的基本代码示例。请确保您根据实际情况修改服务器地址、群组名称以及其他细节。

2023/8/29 20:07:02

请使用uniapp写一个给django websocket互发消息的界面

2023/8/29 20:07:44

以下是使用Uniapp编写的一个简单界面,用于向Django WebSocket发送消息并接收来自服务器的消息。

 
 
<template>
  <view class="container">
    <view class="message-list">
      <text v-for="(message, index) in messages" :key="index">{
   
   { message }}</text>
    </view>
    <input v-model="inputMessage" type="text" placeholder="输入消息" />
    <button @click="sendMessage">发送</button>
  </view>
</template>

<script>
import { connectWebSocket, sendMessage } from '@/utils/websocket.js'

export default {
  data() {
    return {
      messages: [],
      inputMessage: '',
    }
  },
  mounted() {
    connectWebSocket()

    // 监听服务器发送的消息
    uni.$on('websocket-message', (message) => {
      this.messages.push(message)
    })
  },
  methods: {
    sendMessage() {
      if (!this.inputMessage.trim()) {
        return
      }

      sendMessage(this.inputMessage)

      this.inputMessage = '' // 清空输入框
    },
  },
}
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

.message-list {
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
}
</style>

在这个界面中,我们绑定了一个消息列表messages和一个输入框inputMessage。当用户点击发送按钮时,调用sendMessage方法将输入的消息通过WebSocket发送给服务器。同时,我们在页面挂载阶段监听了websocket-message事件,一旦接收到来自服务器的消息,将其添加到消息列表中显示出来。

请确保您已正确配置了WebSocket连接和发送消息的逻辑,并根据实际情况修改相关代码。

2023/8/29 20:16:23

那个听服务器发送的消息代码不起作用

2023/8/29 20:16:43

抱歉,我之前的回答中遗漏了一些代码。请在Uniapp的main.js文件中添加下面的代码来处理WebSocket消息:

 
 

javascript

// main.js

import Vue from 'vue'
import App from './App'

Vue.config.productionTip = false

const app = new Vue({
  ...App,
})

// 监听服务器发送的消息
uni.onSocketMessage((res) => {
  const message = res.data
  uni.$emit('websocket-message', message)
})

app.$mount()

在这段代码中,我们使用uni.onSocketMessage方法监听来自WebSocket的消息,在接收到消息时,将其通过uni.$emit方法发送到名为websocket-message的事件上。然后在页面组件中,我们通过uni.$on监听该事件,并将消息添加到消息列表中显示出来。

请确保您已经在main.js文件中添加了以上的代码,以监听和处理来自WebSocket的消息。

2023/8/29 20:23:38

请将客户端界面的代码美化一下

2023/8/29 20:25:45

以下是美化后的客户端界面代码:

 
 
<template>
  <view class="container">
    <view class="message-list">
      <text v-for="(message, index) in messages" :key="index" class="message-item">{
   
   { message }}</text>
    </view>
    <view class="input-container">
      <input v-model="inputMessage" type="text" placeholder="输入消息" class="input-field" />
      <button @click="sendMessage" class="send-button">发送</button>
    </view>
  </view>
</template>

<script>
import { connectWebSocket, sendMessage } from '@/utils/websocket.js'

export default {
  data() {
    return {
      messages: [],
      inputMessage: '',
    }
  },
  mounted() {
    connectWebSocket()

    // 监听服务器发送的消息
    uni.$on('websocket-message', (message) => {
      this.messages.push(message)
    })
  },
  methods: {
    sendMessage() {
      if (!this.inputMessage.trim()) {
        return
      }

      sendMessage(this.inputMessage)

      this.inputMessage = '' // 清空输入框
    },
  },
}
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.message-list {
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
}

.message-item {
  padding: 10px;
  border-radius: 5px;
  background-color: #fff;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  margin-bottom: 10px;
}

.input-container {
  display: flex;
  align-items: center;
}

.input-field {
  flex: 1;
  padding: 10px;
  border-radius: 5px 0 0 5px;
  border: 1px solid #ccc;
  background-color: #fff;
}

.send-button {
  padding: 10px 20px;
  border-radius: 0 5px 5px 0;
  background-color: #007bff;
  color: #fff;
  border: none;
  cursor: pointer;
}
</style>

在这个美化后的界面中,我们给消息列表项(message-item)添加了样式,使其具有圆角和阴影效果。输入框和发送按钮也都进行了样式调整,使整个界面看起来更加美观。

请将上述代码复制到您的Uniapp项目中,并根据需要进行进一步的样式调整。

2023/8/29 20:28:29

请将输入框和按钮和微信一样固定住

2023/8/29 20:29:24

要将输入框和按钮固定在底部,您可以使用CSS的固定定位(fixed positioning)来实现。以下是更新后的代码块:

 
 
<template>
  <view class="container">
    <view class="message-list">
      <text v-for="(message, index) in messages" :key="index" class="message-item">{
   
   { message }}</text>
    </view>
    <view class="input-container">
      <input v-model="inputMessage" type="text" placeholder="输入消息" class="input-field" />
      <button @click="sendMessage" class="send-button">发送</button>
    </view>
  </view>
</template>

<style>
.container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.message-list {
  display: flex;
  flex-direction: column;
  padding-bottom: 20px; /* 添加底部留白 */
}

.message-item {
  padding: 10px;
  border-radius: 5px;
  background-color: #fff;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  margin-bottom: 10px;
}

.input-container {
  display: flex;
  align-items: center;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 10px;
  background-color: #fff;
}

.input-field {
  flex: 1;
  padding: 10px;
  border-radius: 5px 0 0 5px;
  border: 1px solid #ccc;
  background-color: #fff;
}

.send-button {
  padding: 10px 20px;
  border-radius: 0 5px 5px 0;
  background-color: #007bff;
  color: #fff;
  border: none;
  cursor: pointer;
}
</style>

在这个更新后的代码中,我们使用了固定定位(fixed positioning)将输入框和按钮容器(input-container)固定在页面底部。通过将其position属性设置为fixed,并指定bottom: 0; left: 0; right: 0;来使其始终位于底部,并根据需要进行调整。同时,我们还为消息列表(message-list)添加了底部留白(padding-bottom: 20px;),以避免输入框和按钮遮挡住最后一条消息。

请将更新后的代码复制到您的Uniapp项目中,并根据需要进行进一步的样式调整。

2023/8/29 20:49:54

客户端组聊得时候我怎么测试

2023/8/29 20:50:22

要测试客户端的群组聊天功能,您可以在多个客户端实例中同时打开应用,并加入同一个聊天群组。这样,您可以在其中一个客户端发送消息,然后在其他客户端上接收到该消息。

以下是一些步骤来测试客户端的群组聊天功能:

  1. 启动您的Uniapp应用,并确保已经连接到Django WebSocket服务器。
  2. 在第一个客户端中输入一个昵称,并点击“加入群组”按钮。
  3. 打开另一个客户端应用,并使用相同的群组名称(例如,输入相同的群组名称或使用相同的昵称)。
  4. 点击“加入群组”按钮。
  5. 现在,您可以在任何一个客户端中输入消息,并在其他所有客户端上接收到该消息。

通过这种方式,您可以模拟多个用户同时进行群组聊天,并测试消息的发送和接收功能。

请注意,为了能够正确地进行测试,请确保您已经在Django服务器端实现了群组聊天的逻辑,并将消息发送到群组中的所有成员。并且,您需要根据具体情况修改代码以适配您的应用程序和服务器端实现。

2023/8/29 20:50:56

根据以上的代码 客户端组聊得时候我怎么测试

2023/8/29 20:52:28

要测试基于以上代码的客户端群组聊天功能,您可以按照以下步骤进行操作:

  1. 启动应用程序并连接到Django WebSocket服务器。
  2. 在一个客户端中输入昵称并点击“加入群组”按钮。这将使该客户端加入一个特定的聊天群组。
  3. 打开另一个客户端,并使用相同的群组名称(或者使用不同的昵称和相同的群组名称)加入同一个聊天群组。
  4. 现在,您可以在任何一个客户端中输入消息并点击发送按钮。
  5. 您会注意到,通过WebSocket连接,消息将被发送到Django服务器,并从服务器发送给所有其他客户端,以便它们能够接收到您发送的消息。
  6. 在其他客户端上,您将看到您发送的消息出现在消息列表中。

通过这种方式,您可以模拟多个客户端同时进行群组聊天,并测试消息的发送和接收功能。请确保已正确配置服务器端以便处理群组聊天逻辑,并根据需要修改代码以适应您的实际情况。

2023/8/29 20:56:54

根据以上的代码 请优化服务端和客户端的代码 要求在客户端连接服务端的时候可以指定群组号码

2023/8/29 21:05:40

下面是优化后的服务端和客户端代码,以便在客户端连接服务器时可以指定群组号码:

服务端(Django)代码:

 
 

python

# consumers.py

import json
from channels.generic.websocket import AsyncWebsocketConsumer

class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.group_name = self.scope['url_route']['kwargs'].get('group_id')
        await self.channel_layer.group_add(
            self.group_name,
            self.channel_name
        )
        await self.accept()

    async def disconnect(self, close_code):
        await self.channel_layer.group_discard(
            self.group_name,
            self.channel_name
        )

    async def receive(self, text_data):
        data = json.loads(text_data)
        message = data.get('message')
        # 处理收到的消息,可以根据需要进行逻辑处理
        await self.channel_layer.group_send(
            self.group_name,
            {
                'type': 'chat_message',
                'message': message
            }
        )

    async def chat_message(self, event):
        message = event['message']
        await self.send(text_data=json.dumps({
            'message': message
        }))

客户端(Uniapp)代码:

 
 
<template>
  <view class="container">
    <view class="message-list">
      <text v-for="(message, index) in messages" :key="index" class="message-item">{
   
   { message }}</text>
    </view>
    <view class="input-container">
      <input v-model="inputMessage" type="text" placeholder="输入消息" class="input-field" />
      <button @click="sendMessage" class="send-button">发送</button>
    </view>
  </view>
</template>

<script>
import { connectWebSocket, sendMessage } from '@/utils/websocket.js'

export default {
  data() {
    return {
      messages: [],
      inputMessage: '',
      groupID: 'your_group_id' // 在这里指定群组号码
    }
  },
  mounted() {
    connectWebSocket(this.groupID)

    // 监听服务器发送的消息
    uni.$on('websocket-message', (message) => {
      this.messages.push(message)
    })
  },
  methods: {
    sendMessage() {
      if (!this.inputMessage.trim()) {
        return
      }

      sendMessage(this.inputMessage)

      this.inputMessage = '' // 清空输入框
    },
  },
}
</script>

<style>
/* 样式同上 */
</style>

在服务端代码中,我们使用了URL路由中的group_id参数来获取客户端连接请求中指定的群组号码。然后,我们通过group_add方法将连接添加到相应的群组中,并在接收到消息时,使用group_send方法将消息发送给该群组的所有成员。

在客户端代码中,我们添加了一个groupID变量,用于指定要加入的群组号码。在mounted生命周期钩子中,我们将该群组号码作为参数传递给connectWebSocket函数。这样,客户端将连接到指定的群组,并能够接收和发送消息。

请根据实际情况修改代码并确保服务器端和客户端的代码一致。

2023/8/29 21:08:10

websocket.js还没有更新

export function connectWebSocket(groupID) { socketTask = uni.connectSocket({ url: 'ws://localhost:8000/ws/chat/, // 替换为您的服务器地址 success() { console.log("初始化完成!") } }) }

请问怎么将groupID传入到url路径中

2023/8/29 21:20:42

要将 groupID 传递给 URL 路径,您可以使用字符串拼接或模板字符串来动态构建 URL。以下是示例代码:

 
 

javascript

export function connectWebSocket(groupID) {
  const url = `ws://localhost:8000/ws/chat/${groupID}`; // 使用模板字符串将 groupID 插入到 URL 中

  socketTask = uni.connectSocket({
    url: url,
	
	success() {
		console.log("初始化完成!")
	}
  })
}

在上述示例中,通过使用模板字符串,在 URL 的路径部分使用 ${groupID}groupID 参数插入到 URL 中。这样,groupID 的值会动态地被替换为实际的参数值,并传递给 WebSocket 的 URL。请确保 groupID 的值是有效的以生成正确的 URL。

猜你喜欢

转载自blog.csdn.net/qq_35622606/article/details/132569111