The WebSocket connection carries parameters
时间: 2024-04-22 11:27:52 浏览: 76
The WebSocket Handbook
If you want to pass parameters through the WebSocket connection, you can include them in the URL when establishing the connection. Here's an example of how you can achieve this in the front-end using Vue and the WebSocket API:
```javascript
export default {
data() {
return {
socket: null,
userId: 'your-user-id', // replace with actual user ID
token: 'your-token' // replace with actual token
};
},
created() {
const url = `ws://your-server-address?userId=${this.userId}&token=${this.token}`;
this.socket = new WebSocket(url);
this.socket.onopen = () => {
console.log('Connected to the WebSocket server');
};
this.socket.onmessage = (event) => {
const message = JSON.parse(event.data);
console.log('Received message:', message);
};
this.socket.onclose = () => {
console.log('Disconnected from the WebSocket server');
};
},
// ...
}
```
In this example, the `userId` and `token` parameters are included in the URL when establishing the WebSocket connection. On the server-side, you can extract these parameters from the URL and use them as needed.
Please make sure to replace `'your-server-address'` with the actual WebSocket server address, and `'your-user-id'` and `'your-token'` with the appropriate values for your application. Additionally, ensure that the server-side implementation handles these parameters correctly.
阅读全文