当前位置:网站首页>[FFH] websocket practice of real-time chat room
[FFH] websocket practice of real-time chat room
2022-07-24 08:48:00 【Go to bed after finishing】
【FFH】 Real time chat room WebSocket actual combat
Preface
If you want to realize the same function as wechat chat , It is obviously not enough to communicate within the network , Therefore, the soft bus does not work with this kind of long-distance transmission . If we want to complete the chat function of wechat , The traditional method is to use webSocket Full duplex communication with the help of server .
WebSocket What is it? ?
WebSocket yes One in a single TCP Network communication protocol for full duplex communication on the connection .
There was no such thing as webSocket When , We all use HTTP Protocol for network communication , however HTTP The protocol is a stateless , There is no connection , One-way application layer protocol , Therefore, the client can only make one-way requests to the server , The server cannot actively send messages to the client , As a result, it is difficult for businesses such as real-time chat to carry out .
Developers can use HTTP The scheme of long polling , That is to say, we need HTTP The connection request must be maintained for a period of time , To get the latest server messages . This is obviously inefficient , And it's a waste of resources .
So it was born WebSocket, You only need to connect once , You can always maintain full duplex communication .
Demo Exhibition
Now let's use the official WebSocket Interface to achieve a simple real-time chat room Demo. The effect is as follows :
Code implementation
You can see the interface description in the official document , We only need a few interfaces to realize our business requirements .
https://developer.harmonyos.com/cn/docs/documentation/doc-guides/websocket-connection-0000001333321005

① Apply for network permission
stay config.json Register network permissions in the file , This permission allows the program to open a network socket , Make a network connection .
"reqPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
② Import webSocket modular
import webSocket from '@ohos.net.webSocket';
③ establish webSocket object
Then we call createWebSocket() Interface generates a webSocket object , And save it .
let ws = webSocket.createWebSocket();
④ Connect webSocket passageway
call connect() Interface . I need a URL Pass in as a parameter , In this demo in , Directly use a previously developed server interface to call , But not open to the outside world , Therefore, you only need to put the interface address you have developed into ”wsURL“ Inside you can .
onInit() {
let that = this;
ws.connect("wsURL", (err, value) => {
if (!err) {
console.log("xxx---connect success");
} else {
console.log("xxx---connect fail, err:" + JSON.stringify(err));
}
});
},
⑤ Subscribe to message updates in the channel
Here we call on( type:‘message’ ) Interface for message listening , It should be noted here that the string type passed by the server , So if the message is JSON object , You need to use JSON.parse() To analyze , restore JSON object .
onInit() {
let that = this;
ws.on('message', (err, value) => {
console.log("xxx---on message, message:" + value);
// What is passed is the serialized string , Need to deserialize as JSON object
let dataObj = JSON.parse(value)
console.log("xxx---parse success---postId: "+dataObj.postId+",message:"+dataObj.message)
that.message.push(dataObj)
console.log("xxx---check message: "+JSON.stringify(that.message))
});
},
⑥ Send a message
Next call send() Interface to send messages , Note here , If you want to pass JSON object , To use JSON.stringify() Do serialization , Make sure we pass in the form of a stream string .
In the callback of this interface , We can also print it out , Check whether the message is sent successfully .
sendMessage(){
let that = this;
let data = {
postId:that.id,
message:that.sendMes
}
let dataStr = JSON.stringify(data)
ws.send(dataStr, (err, value) => {
if (!err) {
console.log("xxx---send success");
} else {
console.log("xxx---send fail, err:" + JSON.stringify(err));
}
});
that.message.push(data)
},
⑦ Hide the title bar
Careful friends will find , my demo The black title bar of the display is missing , In fact, it can be hidden , Only need config.json In file module.abilities Add a few lines of code below .
"metaData":{
"customizeData":[
{
"name": "hwc-theme",
"value": "androidhwext:style/Theme.Emui.NoTitleBar",
"extra":""
}
]
}
⑧ Pattern design
Next, simply design the interface style , Render the obtained message .
<div class="container">
<div style="width: 100%;height: 8%;color: #ff86868a;font-size: 25px;justify-content: center;position: absolute;">
<text style="top: 10px;">
Real time chat room
</text>
</div>
<list style="height: 80%;">
<list-item for="{
{message}}" class="{
{$item.postId==id?'listItemRight':'listItemLeft'}}" >
<div class="listItemDiv" >
<text style="padding:5px;border-radius: 10px;font-size: 20px;margin: 5px;max-width: 70%;">
{
{$item.message}}
</text>
</div>
</list-item>
</list>
<div style="position: absolute;left:10px;bottom: 20px;">
<textarea id="textarea" class="textarea" extend="true" placeholder=" Please input chat information " onchange="inputChange" >
</textarea>
<button style="width: 75px;height: 50px;margin-left: 10px;background-color: #ff4848f5;" onclick="sendMessage"> send out </button>
</div>
</div>
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
}
.textarea {
placeholder-color: gray;
width: 70%;
}
.listItemDiv{
background-color: #ff87f3d0;
border-radius: 10px;
}
.listItemLeft{
margin: 10px;
width: 100%;
justify-content: flex-start;
}
.listItemRight{
margin: 10px;
width: 100%;
justify-content: flex-end;
}
边栏推荐
- Relationship between fork and pipeline
- mysql SUBSTRING_ Application of index in business scenarios
- Wargames bandit (21-33) problem solving essay
- G1 (garbage first) collector
- Aquanee: the true meaning of "p2e"
- Digital collections are both outlets and risks!
- Unity解决Package Manager“You seem to be offline”
- Super complete summary: how to operate files in go language
- WordPress free theme: document, making reading more convenient
- Php+spool to realize the shell client of web version
猜你喜欢

Wei Xiaoli's "pursuer" is coming

RPC中实现提供者信息变化后通知消费者

0 threshold takes you to know two-point search

Is gamefi in decline or in the future?

"Solution" friend of Vulcan

How to integrate and use log4net logging plug-in in vs2019 class library

How to use redis' publish subscribe (MQ) in.Netcore 3.1 project

Take out the string in brackets

Houdini notes

JS string interception
随机推荐
Move protocol global health declaration, step into Web3 in sports
Figure storage geabase
Route interceptor
剑指 Offer II 024. 反转链表
Okaleido tiger NFT is about to log in to binance NFT platform, and the era of NFT rights and interests is about to start
「题解」零钱兑换
Four data interaction modes of go grpc
【一起上水硕系列】EE feedback 详解
使用Go语言开发eBPF程序
mysql SUBSTRING_ Application of index in business scenarios
"Solution" friend of Vulcan
【一起上水硕系列】Final RAD-new literacies
[emotion] what is "excellent"
pip3 带源安装大全
Hack the box - Web requests module detailed Chinese tutorial
Summary of points management system project
Kotlin learning note 1 - variables, functions
Local warehouse associated with remote warehouse
The solution of [an error occurred while trying to create a file in the destination directory: access denied] is prompted when installing the software
网络情人