Make writing a habit together! This is the 12th day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

What is a WebSocket?

WebSocket is a data communication protocol similar to HTTP.

People who are new to WebSocket ask the same question: Why do we need another protocol when we already have HTTP? What good can it do?

The simple answer is that the HTTP protocol has a flaw: communication can only be initiated by the client. HTTP is implemented based on request response.

For example, if we want to know today’s weather, the client can only send a request to the server, and the server returns the query result. The HTTP protocol does not allow the server to actively push information to the client.

The nature of this one-way request makes it very difficult for the client to know if the server has continuous state changes. We can only use polling: every once in a while, we issue a query to see if the server has any new information. The most typical scenario is a chat room. But polling is inefficient and wasteful (because you have to connect all the time, or HTTP connections are always open). So engineers have been wondering if there is a better way. That’s how WebSocket was invented.

Introduction of websocket

WebSocket protocol was born in 2008 and became an international standard in 2011. All browsers already support it.

Its biggest characteristic is that the server can take the initiative to push information to the client, the client can also take the initiative to send information to the server, is a real two-way equal dialogue, belongs to a server push technology.

Typical WebSocket application scenarios:

  • Instant messaging….. Customer service
  • Chat room broadcast
  • order

The socket technology

1. The client sends socket requests

0. You can use native 0. You can use package **socket. IO **Copy the code

2. Server: provides socket service

0.  **socket.io**
Copy the code

The basic flow

The use of the WebSocket

1. Download the socket. IO -client package

npm i socket.io-client
Copy the code

2. The server establishes the link

Import IO from 'socket.io-client' const client = IO (' address ', {query: {token: user token}, transports: ['websocket'] })Copy the code

3. The server communicates

Client. On ('connect', () => {}) This event triggers client.on('disconnect', () => {}) // Disconnecting from the server, which triggers disconnect // message, Client. On ('message', () => {}) // Receive a message from the server, Emit ('message', value) // Close the connection to the server.client.close ()Copy the code

Example Write a small chat bot project to practice using Websocket

IO client library:socket.io-client

npm i socket.io-client
Copy the code

2. Create a socket. IO client when entering the robot page

Import IO from 'socket. IO -client' import {getToken} from '@/utils/storage' const [messageList, setMessageList] = useState< {type: 'robot' | 'user'text: string}[]>([ { type: 'robot', text: }, {type: 'user', text: 'hello'}]) / / used to cache the socket. IO client instance const clientRef = useRef < socket | null > (null) / / with the aid of uesEffect side effects, UseEffect (() => {const client = IO ('http://#########', {transports: ['websocket'], // Pass token in query string argument query: {token: GetToken ().token}}) // Listen for successful connection event client.on('connect', SetMessageList (messageList => [...messageList, {type: 'robot', text: 'I now await your questions. On ('message', data => {console.log('>>>> received socket. IO message :', data)}) Return () => {client.close()}}, []) return () => {client.close()}}, []Copy the code

To send messages to robots, using instances of socket. IOemit()Method to send information

Declare a state and bind the message input box

Const [message, const [message, SetMessage] = useState(" ") <Input className="no-border" placeholder=" value={message} onChange={e => setMessage(e)} />Copy the code

2. Add keyboard events to the message input box to send messages when entering enter

<Input onKeyUp={onSendMessage}/> // Send a message const onSendMessage = () => {console.log(value) if (value.trim() === ") { return } // 1. Message ioRef. Current? .emit('message', { msg: value, timestamp: Date.now() }) // 2. SetMessageList ([...messageList, {type: 'user', text: value}]) // 3. Empty the setValue (' ')}Copy the code

Receive messages returned by the robot

IO listens for the reply message and adds it to the chat list, listens for the message event to the socket. IO instance, receives the message in the event callback, and adds the status

On ('message', (data) => {setMessageList((messageList) => [...messageList, { type: 'robot', text: data.msg }, ]) })Copy the code