The server uses django websocket and the client uses uniapp. Please provide reference notes on how to write the code for the server and client groups to send messages to each other.

2023/8/29 19:21:11

The server uses django websocket and the client uses uniapp. How do I write the code for the server and client groups to send messages to each other?

2023/8/29 19:22:25

In the case of using Django WebSocket on the server side and Uniapp on the client side, the following is a code example to implement group messaging between the server and client.

Server side code (using Django Channels library):

  1. First, configure Channels in Django’s settings.py file:
 
 

python

# settings.py

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

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels.layers.InMemoryChannelLayer",
    },
}
  1. Create a consumers.pyfile and define the WebSocket consumer class:
 
 

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.pyConfigure URL routing in the file :
 
 

python

# routing.py

from django.urls import re_path

from . import consumers

websocket_urlpatterns = [
    re_path(r'ws/chat/$', consumers.ChatConsumer.as_asgi()),
]
  1. Run the Django development server:
 
 

shell

python manage.py runserver

Client code (using Uniapp):

  1. Create a WebSocket service file in the uniapp project:
 
 

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. Introduce the WebSocket service file into the page or component that needs to use WebSocket, and call the function to establish the connection and send the message:
 
 
<template>
  <button @click="sendChatMessage">发送消息</button>
</template>

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

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

The above is a basic code example for using Django WebSocket and Uniapp to implement group messaging between the server and the client. Please make sure you modify the server address, group name, and other details according to your actual situation.

2023/8/29 20:07:02

Please use uniapp to write an interface for sending messages to django websocket.

2023/8/29 20:07:44

Below is a simple interface written using Uniapp for sending messages to Django WebSocket and receiving messages from the server.

 
 
<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>

In this interface, we bind a message list messagesand an input box inputMessage. When the user clicks the send button, sendMessagethe method is called to send the entered message to the server via WebSocket. At the same time, we listen for websocket-messageevents during the page loading phase, and once a message is received from the server, we add it to the message list and display it.

Please ensure that you have correctly configured the WebSocket connection and message sending logic, and modify the relevant code according to the actual situation.

2023/8/29 20:16:23

That code that listens to messages sent by the server doesn't work

2023/8/29 20:16:43

Sorry, I missed some code from my previous answer. Please add the following code in Uniapp's main.js file to handle WebSocket messages:

 
 

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()

In this code, we use uni.onSocketMessagea method to listen for messages from WebSocket, and when a message is received, we uni.$emitsend it to websocket-messagean event named via the method. Then in the page component, we uni.$onlisten to the event and add the message to the message list to display it.

Please make sure you have added the above code in your main.js file to listen and handle messages from WebSocket.

2023/8/29 20:23:38

Please beautify the code of the client interface

2023/8/29 20:25:45

The following is the beautified client interface code:

 
 
<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>

In this beautified interface, we added styles to the message list item (message-item) to give it rounded corners and a shadow effect. The input box and send button have also been styled to make the entire interface look more beautiful.

Please copy the above code into your Uniapp project and make further styling adjustments as needed.

2023/8/29 20:28:29

Please fix the input box and button like WeChat

2023/8/29 20:29:24

To fix input boxes and buttons to the bottom, you can use CSS fixed positioning. Here is the updated code block:

 
 
<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>

In this updated code, we use fixed positioning to fix the input box and input-container to the bottom of the page. Specify that it is always at the bottom by setting its positionproperties to , and adjust it as needed. At the same time, we also added a bottom margin ( ) to the message list (message-list) to prevent input boxes and buttons from blocking the last message.fixedbottom: 0; left: 0; right: 0;padding-bottom: 20px;

Please copy the updated code into your Uniapp project and make further styling adjustments as needed.

2023/8/29 20:49:54

How do I test when the client group is chatting?

2023/8/29 20:50:22

To test the client's group chat functionality, you can open the app in multiple client instances simultaneously and join the same chat group. This way you can send a message on one of the clients and receive it on the other client.

Here are some steps to test the client's group chat functionality:

  1. Start your Uniapp application and make sure it is connected to the Django WebSocket server.
  2. Enter a nickname in the first client and click the "Join Group" button.
  3. Open another client app and use the same group name (for example, enter the same group name or use the same nickname).
  4. Click the "Join Group" button.
  5. Now you can enter a message in any one client and receive it on all other clients.

This way you can simulate multiple users in a group chat at the same time and test sending and receiving messages.

Please note that in order to be able to test correctly, make sure you have implemented the group chat logic on the Django server side and send messages to all members of the group. Also, you need to modify the code to suit your application and server-side implementation.

2023/8/29 20:50:56

According to the above code, how can I test when the client group chats?

2023/8/29 20:52:28

To test the client group chat functionality based on the code above, you can follow these steps:

  1. Start the application and connect to the Django WebSocket server.
  2. Enter a nickname in a client and click the "Join Group" button. This will join the client to a specific chat group.
  3. Open another client and join the same chat group using the same group name (or a different nickname and the same group name).
  4. Now you can enter your message in either client and hit the send button.
  5. You'll notice that over the WebSocket connection, messages are sent to the Django server and from the server to all other clients so that they can receive the message you send.
  6. On other clients, you will see the messages you sent appear in the message list.

This way you can simulate multiple clients having group chats at the same time and test sending and receiving messages. Please make sure that the server side is configured correctly to handle the group chat logic and modify the code as needed to suit your situation.

2023/8/29 20:56:54

According to the above code, please optimize the code requirements of the server and client. The client can specify the group number when connecting to the server.

2023/8/29 21:05:40

The following is the optimized server and client code so that the group number can be specified when the client connects to the server:

Server-side (Django) code:

 
 

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
        }))

Client (Uniapp) code:

 
 
<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>

In the server-side code, we use group_idthe parameters in the URL routing to obtain the group number specified in the client connection request. We then group_addadd the connection to the appropriate group via a method and when a message is received, use group_senda method to send the message to all members of the group.

In the client code, we added a groupIDvariable that specifies the group number to join. In mountedthe lifecycle hook, we pass the group number as a parameter to connectWebSocketthe function. This way, the client will connect to the specified group and be able to receive and send messages.

Please modify the code according to the actual situation and ensure that the server-side and client-side codes are consistent.

2023/8/29 21:08:10

websocket.js has not been updated yet

export function connectWebSocket(groupID) { socketTask = uni.connectSocket({ url: 'ws://localhost:8000/ws/chat/, // Replace with your server address success() { console.log("Initialization completed! ") } }) }

How do I pass the groupID into the url path?

2023/8/29 21:20:42

To groupIDpass a URL path, you can use string concatenation or template strings to dynamically build the URL. Here is sample code:

 
 

javascript

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

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

${groupID}In the above example, the parameter is groupIDinserted into the URL by using a template string in the path portion of the URL . In this way, groupIDthe value of will be dynamically replaced with the actual parameter value and passed to the WebSocket URL. Please make sure groupIDthe value of is valid to generate the correct URL.

Guess you like

Origin blog.csdn.net/qq_35622606/article/details/132569111