WebSocket is a technology that allows two-way communication by keeping the server and client always connected, so WebSocket can both send data and receive data. In this article, we will take a look at how Send and receive data using WebSocket.
Let’s take a look at How to send text data?
Use the freely available echo.websocket.org as a sample
The specific example is as follows
var connection = new WebSocket('wss://echo.websocket.org'); connection.send('样本数据');
In this example, to see that the WebSocket is being created instance and use the send() method to send data.
However, data should generally be transferred at any time.
So if you want to send the data entered in the form by clicking a button, you can write it as follows.
btn.addEventListener('click', function(e) { var text = document.getElementById('text'); connection.send(text.value); })
In this example, we get the string entered into the form and apply it to the parameters of send().
In this way, you can send arbitrary text data.
How to receive text data?
The test server Echo.websocket.org used this time will return the transmitted data as is.
The code is as follows
connection.onmessage = function(e) { console.log(e.data); };
We use the onmessage() event, which is used to receive messages from four types of event processing.
Although this is a simple description, this alone can receive data returned from the server.
By the way, when you use the close() method together, the encoding is as follows
connection.onmessage = function(e) { console.log(e.data); connection.close(); };
In this case, the communication is disconnected immediately after receiving the data.
At this time, it should be noted that if close() disconnects communication, communication will not be possible unless the connection is established with WebSocket again!
The above is the detailed content of How to send and receive data using WebSocket. For more information, please follow other related articles on the PHP Chinese website!