Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement chat tools based on Serverless and Websocket

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

How to implement chat tools based on Serverless and Websocket, many novices are not very clear about this. In order to help you solve this problem, the following editor will explain it in detail. People with this need can come and learn. I hope you can get something.

It is not difficult for traditional business to implement Websocket, but function computing is basically event-driven and does not support long link operations. If the function calculation is combined with the API gateway, can there be an implementation scheme for Websocket?

API Gateway trigger to implement Websocket

WebSocket protocol is a new network protocol based on TCP. It implements full-duplex (full-duplex) communication between the browser and the server, that is, allowing the server to actively send information to the client. WebSocket can actively send data to the client when there is a need for data push on the server side. However, the server of the original HTTP protocol can only get the data that needs to be pushed to the client by polling or long poll.

Because the cloud function is stateless and runs in a trigger mode, it will only be triggered when an event arrives. Therefore, in order to achieve WebSocket, the cloud function SCF is combined with the API gateway to undertake and maintain the connection with the client through the API gateway. You can think that the cloud function implements the server side together with the API gateway. When a message is sent from the client, it will be passed to the API gateway first, and then the API gateway will trigger the cloud function to execute. When the server cloud function wants to send a message to the client, the cloud function will first POST the message to the reverse push link of the API gateway, and then the API gateway will push the message to the client.

The specific implementation architecture is as follows:

For the entire lifecycle of WebSocket, it mainly consists of the following events:

Connection establishment: the client requests the server to establish the connection and complete the connection establishment

Data uplink: the client sends data to the server through the established connection

Data downlink: the server sends data to the client through the established connection

Client disconnect: the client is required to disconnect the established connection

Server disconnect: the server is required to disconnect the established connection.

For events in the entire lifecycle of WebSocket, SCF and API gateway are handled as follows:

Connection establishment: the client establishes a WebSocket connection with the API gateway, and the API gateway sends the connection establishment event to the SCF

Data uplink: the client sends data through WebSocket, and the API gateway forwards the data to SCF

Data downlink: SCF sends a request to the push address specified by the API gateway. After receiving it, the API gateway will send the data to the client through WebSocket.

Client disconnect: the client requests to disconnect, and the API gateway sends the disconnect event to SCF

Server disconnection: SCF sends a disconnect request to the push address specified by the API gateway, and the API gateway disconnects the WebSocket connection when it is received.

Therefore, the interaction between cloud functions and API gateways needs to be hosted by three types of cloud functions:

Registration function: this function is triggered when a WebSocket connection is established between the client initiating and the API gateway to notify the secConnectionID of the SCF WebSocket connection. This function usually records secConnectionID to persistent storage, which is used for reverse push of subsequent data.

Cleanup function: this function is triggered when the client initiates an WebSocket connection interruption request, notifying SCF of the secConnectionID that is ready to disconnect. This function usually cleans up the secConnectionID recorded in the persistent store

Transfer function: this function is triggered when the client sends data over a WebSocket connection, informing SCF of the secConnectionID of the connection and the data sent. Business data is usually processed in this function. For example, whether to push data to other secConnectionID in persistent storage.

Websocket function realization

According to the overall architecture diagram of this feature provided by Tencent Cloud official website:

Here we can use the object store COS as a persistence solution. When a user establishes a link store ConnectionId to COS, the user disconnects and deletes the link ID.

Where the registration function:

#-*-coding: utf8-*-import osfrom qcloud_cos_v5 import CosConfigfrom qcloud_cos_v5 import CosS3Clientbucket = os.environ.get ('bucket') region = os.environ.get (' region') secret_id = os.environ.get ('secret_id') secret_key = os.environ.get (' secret_key') cosClient = CosS3Client (CosConfig (Region=region, SecretId=secret_id, SecretKey=secret_key) def main_handler (event Context): print ("event is% s"% event) connectionID = event ['websocket'] [' secConnectionID'] retmsg = {} retmsg ['errNo'] = 0 retmsg [' errMsg'] = "ok" retmsg ['websocket'] = {"action": "connecting", "secConnectionID": connectionID} cosClient.put_object (Bucket=bucket, Body='websocket'.encode ("utf-8") Key=str (connectionID), EnableMD5=False) return retmsg

Transfer function:

#-*-coding: utf8-*-import osimport jsonimport requestsfrom qcloud_cos_v5 import CosConfigfrom qcloud_cos_v5 import CosS3Clientbucket = os.environ.get ('bucket') region = os.environ.get (' region') secret_id = os.environ.get ('secret_id') secret_key = os.environ.get (' secret_key') cosClient = CosS3Client (CosConfig (Region=region, SecretId=secret_id) SecretKey=secret_key)) sendbackHost = os.environ.get ("url") def Get_ConnectionID_List (): response = cosClient.list_objects (Bucket=bucket,) return [eve ['Key'] for eve in response [' Contents']] def send (connectionID Data): retmsg = {} retmsg ['websocket'] = {} retmsg [' websocket'] ['action'] = "data send" retmsg [' websocket'] ['secConnectionID'] = connectionID retmsg [' websocket'] ['dataType'] =' text' retmsg ['websocket'] [' data'] = data requests.post (sendbackHost, json=retmsg) def main_handler (event) Context): print ("event is% s"% event) connectionID_List = Get_ConnectionID_List () connectionID = event ['websocket'] [' secConnectionID'] count = len (connectionID_List) data = event ['websocket'] [' data'] + "(= = Online people:" + str (count) + "= =)" for ID in connectionID_List: if ID! = connectionID: send (ID, data) return "send success"

Cleanup function:

#-*-coding: utf8-*-import osimport requestsfrom qcloud_cos_v5 import CosConfigfrom qcloud_cos_v5 import CosS3Clientbucket = os.environ.get ('bucket') region = os.environ.get (' region') secret_id = os.environ.get ('secret_id') secret_key = os.environ.get (' secret_key') cosClient = CosS3Client (CosConfig (Region=region, SecretId=secret_id, SecretKey=secret_key) sendbackHost = os.environ.get ("url") def main_handler (event Context): print ("event is% s"% event) connectionID = event ['websocket'] [' secConnectionID'] retmsg = {} retmsg ['websocket'] = {} retmsg [' websocket'] ['action'] = "closing" retmsg [' websocket'] ['secConnectionID'] = connectionID requests.post (sendbackHost, json=retmsg) cosClient.delete_object (Bucket=bucket, Key=str (connectionID),) return event

The Yaml file is as follows:

Conf: component: "serverless-global" inputs: region: ap-guangzhou bucket: secret_key: myBucket: component:'@ serverless/tencent-cos' inputs: bucket: ${Conf.bucket} region: ${Conf.region} restApi: component:'@ serverless/tencent-apigateway' inputs: region: ${Conf.region} protocols:-http-https serviceName : ChatDemo environment: release endpoints:-path: / method: GET protocol: WEBSOCKET serviceTimeout: 800function: transportFunctionName: ChatTrans registerFunctionName: ChatReg cleanupFunctionName: ChatCleanChatReg: component: "@ serverless/tencent-scf" inputs: name: ChatReg codeUri:. / code handler: reg.main_handler runtime: Python3.6 region: ${Conf.region} environment: Variables: region: ${Conf.region} bucket: ${Conf.bucket} secret_id: ${Conf.secret_id} secret_key: ${Conf.secret_key} url: http://set-gwm9thyc.cb-guangzhou.apigateway.tencentyun.com/api-etj7lhtwChatTrans: component: "@ serverless/tencent-scf" inputs: name: ChatTrans codeUri:. / code handler: trans. Main_handler runtime: Python3.6 region: ${Conf.region} environment: variables: region: ${Conf.region} bucket: ${Conf.bucket} secret_id: ${Conf.secret_id} secret_key: ${Conf.secret_key} url: http://set-gwm9thyc.cb-guangzhou.apigateway.tencentyun.com/api-etj7lhtwChatClean: component: "@ serverless/ Tencent-scf "inputs: name: ChatClean codeUri:. / code handler: clean.main_handler runtime: Python3.6 region: ${Conf.region} environment: variables: region: ${Conf.region} bucket: ${Conf.bucket} secret_id: ${Conf.secret_id} secret_key: ${Conf.secret_key} url: http://set- Gwm9thyc.cb-guangzhou.apigateway.tencentyun.com/api-etj7lhtw

Note that the API gateway needs to be deployed first. When the deployment is completed, obtain the push back address, and write the push back address in the form of url to the environment variable of the corresponding function:

In theory, you can get the url automatically through ${restApi.url [0] .secure Domain}, but I didn't succeed in getting the url. I had to deploy the API gateway first, get it to this address, and then redeploy it.

After deployment, we can write HTML code to implement visual Websocket Client. The core JavaScript code is:

_ window.onload = function () {var conn; var msg = document.getElementById ("msg"); var log = document.getElementById ("log"); function appendLog (item) {var doScroll = log.scrollTop = = log.scrollHeight-log.clientHeight; log.appendChild (item); if (doScroll) {log.scrollTop = log.scrollHeight-log.clientHeight } document.getElementById ("form"). Onsubmit = function () {if (! conn) {return false;} if (! msg.value) {return false;} conn.send (msg.value); / / msg.value = ""; var item = document.createElement ("div") Item.innerText = "send ↑:"; appendLog (item); var item = document.createElement ("div"); item.innerText = msg.value; appendLog (item); return false;} If (window ["WebSocket"]) {/ / replace with websocket connection address conn = new WebSocket ("ws://service-01era6ni-1256773370.gz.apigw.tencentcs.com/release/"); conn.onclose = function (evt) {var item = document.createElement ("div"); item [XSS _ clean] = "Connection closed."; appendLog (item);} Conn.onmessage = function (evt) {var item = document.createElement ("div"); item.innerText = "receive ↓:"; appendLog (item); var messages = evt.data.split ('n'); for (var I = 0; I < messages.length) ITunes +) {var item = document.createElement ("div"); item.innerText = messages [I]; appendLog (item);}};} else {var item = document.createElement ("div"); item [XSS _ clean] = "Your browser does not support WebSockets."; appendLog (item);}}

When you are done, we open two pages to test:

The practice of Websocket through cloud function + API gateway is definitely not just a chat tool, it can be used in many aspects, such as the production of real-time log system through Websocket.

Separate function computing is only a computing platform, only when combined with the surrounding BaaS, can it show the value and real capability of the Serverless architecture. This is one of the reasons why many people say Serverless=FaaS+BaaS.

Look forward to more partners, through the Serverless architecture, to create more interesting applications.

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report