How to use WebSocket to implement chat function in Vue technology development
2.1 Install Vue
Use the following command to install Vue:
npm install vue
2.2 Install the WebSocket client library
Use the following command to install the WebSocket client library:
npm install vue-native-websocket
import Vue from 'vue' import VueNativeSock from 'vue-native-websocket' Vue.use(VueNativeSock, 'ws://localhost:3000', { connectManually: true, // 手动连接 reconnection: true, // 自动重连 reconnectionAttempts: 5, // 重连尝试次数 }) new Vue({ render: h => h(App), }).$mount('#app')
Here, we set the WebSocket connection address to 'ws://localhost:3000', you can modify it according to the actual situation.
{{ message.content }}
In the above code, we use the v-for directive to render each chat message to the interface, and bind the content of the input box through the v-model directive. When the send button is clicked, the sendMessage function is called to send the entered message to the server.
const WebSocket = require('ws') const wss = new WebSocket.Server({ port: 3000 }) wss.on('connection', (ws) => { ws.on('message', (message) => { wss.clients.forEach((client) => { client.send(message) }) }) })
In the above code, we listen to port 3000. When a client connects, the connection event will be triggered. When a message sent by a client is received, the message is broadcast to all connected clients.
npm run serve
Visit http://localhost:8080 in the browser to see the chat interface.
The above is the detailed content of How to use WebSocket to implement chat function in Vue technology development. For more information, please follow other related articles on the PHP Chinese website!