Cloud web running point to point private chat minimalist demo


These two days to help my friend’s customers to improve the im project chain missing web version, so there is this article, I putgit historyAfter deleting a node on, I think it may be used in the future, and it is convenient for others to open source it. It is not difficult in itself, and can be used as a demonstration or feasibility test.

The app used in this_ Key and app_ Secret is a beta version, only 100 shares. If it’s OK, don’t make trouble. Thank you.

Source code



cloneOr download the source package, open the CD and enter.

npm iorcnpm i

Open http://localhost : 8888 and http://localhost :8888/ test.html Test the chat between root and test.

Other instructions 。

Simple interpretation of source code

The original project is to support private chat and group chat and other complex functions, here is a simple one-to-one chat, so the code is very simplified.

The main difficulties are as follows:

  • The server gets the token and returns it to the front end
  • Front end monitoring related status and information

First, the server side. The corresponding file is server.js There are two pits

App requested from rongyun_ The key is placed in the headers, and the post content format is formdata

Question 1: because I stepped on it, in fact, it’s not careful. I hope you don’t have to step on it.

Question 2: look at the code

Request encryption of key parameters

const app_ Secret = 'cloud Melting [app]_ key]'
const signAppKey = (nonce, timestamp) => {
  let base = app_secret + nonce + timestamp
  return enc.Hex.stringify(SHA1(base))

Depending on the crypto JS package of NPM, it provides enc and SHA1.

Other problems can see the source code, nothing too special.

Then there is the front end, mainly the CV strategy of official documents.

The biggest pit is the call order of the command

  • initialization
  • monitor
  • Get token
  • connect
  • Communication or pull related data

Well, believe me, you’ll step on it.

Connection status monitoring, responsible for friendly prompt:

//Connection status monitoring
  onChanged: (status) => {
    //Status identifies the current connection state
    switch(status) {
      case RongIMLib.ConnectionStatus.CONNECTED:
        console.log ('link successful ')
      case RongIMLib.ConnectionStatus.CONNECTING:
        console.log ('linking ')
      case RongIMLib.ConnectionStatus.DISCONNECTED:
        console.log ('disconnect ')
      case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
        console.log ('other devices log in, local is kicked')
      case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
        console.log ('the domain name is incorrect, please check the security domain name configuration in the developer background')
      case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
        console.log ('the network is not available, you can call connect to reconnection')
        console.log ('link status is', status)

Information receiving and monitoring, responsible for page logic:

//Receive message listen
  //Message received
  onReceived: res => {
    let messageContent = res.content
    //Judge message type
    switch(res.messageType) {
      case  RongIMClient.MessageType.TextMessage : // text message
        console.log ('text content', messageContent.content )
        // res.senderUserId
      case  RongIMClient.MessageType.ImageMessage : // picture message
        console.log ('picture thumbnail Base64 ', messageContent.content )
        console.log ('source URL ', messageContent.imageUri )
      case  RongIMClient.MessageType.HQVoiceMessage : // audio message
        console.log ('audio type ', messageContent.type )// encoding and decoding type. The default is aac audio
        console.log ('audio URL ', messageContent.remoteUrl )// play: < audio SRC = {remoteurl} / >
        console.log ('audio duration', messageContent.duration )
      case  RongIMClient.MessageType.RichContentMessage : // rich text (text) message
        console.log ('text content', messageContent.content )
        console.log ('picture Base64', messageContent.imageUri )
        console.log ('source URL ', messageContent.url )
      case  RongIMClient.MessageType.UnknownMessage : // unknown message
        console.log ('unknown message, please check whether the custom format of the message is correct', message)
        console.log ('received message', RES)

And then there’s the connection:

//Cloud connectivity
RongIMClient.connect(token, {
  onSuccess: (userId) => {
    console.log ('connection succeeded, user ID is', userid)
  onTokenIncorrect: () => {
    console.log ('connection failed, reason: invalid token ')
  onError: (errorCode) => {
    let info = ''
    switch(errorCode) {
      case RongIMLib.ErrorCode.TIMEOUT:
        Info: 'link timeout'
      case RongIMLib.ConnectionState.UNACCEPTABLE_PAROTOCOL_VERSION:
        Info: 'unacceptable protocol version'
      case RongIMLib.ConnectionState.IDENTIFIER_REJECTED:
        Info: 'incorrect appkey'
      case RongIMLib.ConnectionState.SERVER_UNAVAILABLE:
        Info: 'server not available'
        info = errorCode
    console.log ('connection failed, failure reason:', info)

Note that userid is unique and integrated into cloud project library. Name and portaituri are required. These things should be extracted from your database user cross reference information, userid must be unique.

Other code is the normal page rendering and so on, no more details.

be careful

For the convenience of rewriting, the JS part of the front-end code uses ES6. IE and safari are not applicable.