How to send messages using websocket on the front end

Time:2024-3-4

preamble

Learn how to send messages using websocket on the front-end today!

1 Introduction to the Basics

1.1 What is WebSocket

WebSocket is a protocol for full-duplex communication over a single TCP connection that allows real-time, two-way communication between a client and a server. Unlike traditional HTTP requests, WebSocket uses a long connection to maintain a persistent connection between the client and the server, allowing data to be sent and received in real time.
In WebSocket, clients and servers can send messages to each other. Clients can use the WebSocket API in JavaScript to send messages to the server and receive messages from the server.

1.2 Code Examples

The following is a code example of sending a message using the WebSocket API:
var socket = new WebSocket("ws://example.com/socketserver");

socket.onopen = function(event) {
  socket.send("Hello server!");
};

socket.onmessage = function(event) {
  console.log("Received message from server: " + event.data);
};

socket.onerror = function(event) {
  console.log("WebSocket error: " + event.error);
};

socket.onclose = function(event) {
  console.log("WebSocket connection closed with code " + event.code);
};
In the code above, a WebSocket object is first created, specifying the address of the server. Then, a WebSocket object is created in theonopen The callback function sends a message to the server. When the server sends a message to the client, theonmessage The callback function is triggered so that messages sent by the server can be processed. If an error occurs or the connection is closed, theonerror respond in singingonclose The callback function will be triggered so that these events can be handled. It is important to note that a WebSocket connection must be established before a message can be sent using a WebSocket. In the code above, the connection is established by creating a WebSocket object, and then adding a new WebSocket object to theonopen callback function to send messages to the server. If you try to send messages before the connection is established, they will not be sent successfully.

2 Case Studies

2.1 How vue sends requests using websocket

To use WebSocket in Vue, you can leverage theWebSocket object to create the WebSocket connection and pass thesend() method sends a message to the server.
Here’s a basic Vue component that demonstrates how to send and receive messages using WebSocket:
<template>
  <div>
    <input v-model="message" @keyup.enter="sendMessage">
    <button @click="sendMessage">Send</button>
    <ul>
      <li v-for="msg in messages">{{ msg }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: '',
      messages: [],
      socket: null
    }
  },
  created() {
    this.socket = new WebSocket('ws://localhost:3000')
    this.socket.addEventListener('message', this.handleMessage)
  },
  beforeDestroy() {
    this.socket.close()
  },
  methods: {
    sendMessage() {
      this.socket.send(this.message)
      this.message = ''
    },
    handleMessage(event) {
      this.messages.push(event.data)
    }
  }
}
</script>
In the code above, the
  • first increated A WebSocket object is created in the hook function and a message handler is addedhandleMessage
  • insendMessage method that sends the user input to the server.
  • inhandleMessage method to add the message received from the server to themessages array so that it can be displayed in the interface.
  • Before the component is destroyed, it needs to call theclose() method closes the WebSocket connection.
Note that when using WebSocket, you need to consider cross-domain issues. If the URL of the WebSocket connection is different from the URL of the current page, then you need to set up cross-domain settings on the server side. Also, you need to pay attention to the format of the data when sending and receiving messages, and usually need to convert the data to a JSON string for transmission.

2.2 How to assemble this.message

In the Vue component above, thethis.message is the text of the message entered by the user, which can be customized by binding thev-model Realize two-way binding.
When the user enters a message, the message text can be sent directly to the server. Before sending the message, the message can be assembled as needed, e.g., by adding information such as the sender of the message, the time, etc., for better processing on the server side. The following is an example, assuming that the message to be sent is formatted as a JSON object containing text and a timestamp:
<template>
  <div>
    <input v-model="message.text" @keyup.enter="sendMessage">
    <button @click="sendMessage">Send</button>
    <ul>
      <li v-for="msg in messages">{{ msg.text }} ({{ msg.timestamp }})</li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: {
        text: '',
        timestamp: null
      },
      messages: [],
      socket: null
    }
  },
  created() {
    this.socket = new WebSocket('ws://localhost:3000')
    this.socket.addEventListener('message', this.handleMessage)
  },
  beforeDestroy() {
    this.socket.close()
  },
  methods: {
    sendMessage() {
      this.message.timestamp = new Date().toISOString()
      const json = JSON.stringify(this.message)
      this.socket.send(json)
      this.message.text = ''
      this.message.timestamp = null
    },
    handleMessage(event) {
      const msg = JSON.parse(event.data)
      this.messages.push(msg)
    }
  }
}
</script>
In the code above, the
  • this.message is a file that containstext respond in singingtimestamp An object with two attributes that assigns the message text after the user enters the message to thetext Properties.
  • Before sending a message, assign the current timestamp to thetimestamp property and converts the message object to a JSON string, which is then sent out over a WebSocket.
  • After receiving a message from the server, the JSON string is parsed into a message object and the message object is added to themessages array so that it can be displayed in the interface.

2.3 Sending examples

To send this:
{
"msg_id": "1",
"msg_type": "test",
"content": {
"count": "10"
}
}

code implementation

To send this JSON data, you can convert it to a string and then send it out via WebSocket. The following is a sample code that assumes the use ofaxios library to send WebSocket requests:
import axios from 'axios'

const ws = new WebSocket('ws://localhost:3000')

ws.onopen = () => {
  const data = {
    msg_id: '1',
    msg_type: 'test',
    content: {
      count: '10'
    }
  }
  const jsonString = JSON.stringify(data)
  ws.send(jsonString)
}

ws.onmessage = (event) => {
  const response = JSON.parse(event.data)
  console.log('Received message:', response)
}

ws.onerror = (error) => {
  console.error('WebSocket error:', error)
}

function sendWebSocketRequest(data) {
  const jsonString = JSON.stringify(data)
  ws.send(jsonString)
}

export default {
  sendWebSocketRequest
}
In the code above, the
  • A WebSocket object is first created and theonopen A WebSocket request is sent in the callback function.
  • inonmessage The response data returned by the server is processed in the callback function.
  • inonerror WebSocket errors are handled in the callback function.

make superior

For ease of use, the code for sending WebSocket requests is encapsulated in thesendWebSocketRequest function, which can be called directly from another component to send a WebSocket request. Example:
import { sendWebSocketRequest } from '@/api/websocket'

sendWebSocketRequest({
  msg_id: '1',
  msg_type: 'test',
  content: {
    count: '10'
  }
}).then(response => {
  console.log('Received response:', response)
}).catch(error => {
  console.error('WebSocket error:', error)
})
In the code above, the call tosendWebSocketRequest function sends a WebSocket request and prints the corresponding log when the request succeeds or fails.

2.4 Receiving Example

The return parameter is this, how do I receive it:
{
"msg_id": "1",
"msg_type": "test",
"code": 0,
"err_msg": "Success.",
"content": {
"count": "20"
}
}

code implementation

To receive and process the JSON data returned by the server, you can add the following to theonmessage The received message is processed in the callback function. The following is a sample code that assumes the use ofaxios library to send WebSocket requests:
import axios from 'axios'

const ws = new WebSocket('ws://localhost:3000')

ws.onopen = () => {
  const data = {
    msg_id: '1',
    msg_type: 'test',
    code: 0,
    err_msg: 'Success.',
    content: {
      count: '20'
    }
  }
  const jsonString = JSON.stringify(data)
  ws.send(jsonString)
}

ws.onmessage = (event) => {
  const response = JSON.parse(event.data)
  console.log('Received message:', response)

  // Processing the returned data
  if (response.code === 0) {
    console.log('Success:', response.content)
  } else {
    console.error('Error:', response.err_msg)
  }
}

ws.onerror = (error) => {
  console.error('WebSocket error:', error)
}

function sendWebSocketRequest(data) {
  const jsonString = JSON.stringify(data)
  ws.send(jsonString)
}

export default {
  sendWebSocketRequest
}
In the code above, using theJSON.parse() method converts the incoming message into a JSON object, and theonmessage The returned data is processed in the callback function. If the returned data in thecode attribute is 0, the request was successful and the returned data can be printed on the console; otherwise, the request failed and an error message can be printed on the console.