快速实现消息收发

更新时间: 2024/12/20 17:34:53

网易云信即时通讯(IM)产品提供一整套即时通讯基础能力,助您快速实现多样化的即时通讯场景。本文主要介绍通过集成客户端 SDK(NetEase IM SDK,简称 NIM SDK)并调用 API,快速实现收发消息功能。

支持平台

本文内容适用的开发平台或框架如下所示:

Android iOS macOS/Windows Web/uni-app/小程序 Node.js/Electron HarmonyOS Flutter
✔️️ ✔️️ ✔️️ ✔️️ ✔️️ ✔️ ✔️

环境准备

NIM SDK 兼容的平台和框架系统版本如下所示:

  • 兼容 Android 5.0 及以上版本。
  • 兼容 iOS 9.0 及以上版本,可使用 iPhone/iPad 真机或模拟器。
  • 兼容 HarmonyOS SDK API 11 及以上,运行环境 HarnomyOS NEXT 2.1.2.5(Canary1)以上。兼容 DevEco Studio NEXT Developer Beta1(5.0.3.300)及以上。
  • 兼容 Windows7 及以上,支持 x86_64、x86 架构。
  • 兼容 macOS 10.13 及以上,支持 x86_64、arm64 架构。
  • 兼容微软 IE(9+)、谷歌 Chrome(4+)、微软 Edge(12+)、Mozilla Firefox(11+)、苹果 Safari(5+)、DCloud uni-app、微信/支付宝/百度/抖音小程序。
  • 兼容 Dart 2.17.0 ~ 4.0.0 版本。

前提条件

根据本文操作前,请确保您已经完成了以下设置:

流程概览

单聊/群聊收发消息

实现单聊/群聊收发消息的流程,可分为下图所示的步骤。

普通消息.png

聊天室收发消息

实现聊天室收发消息的流程,可分为下图所示的步骤。

聊天室.png

圈组收发消息

实现圈组收发消息的流程,可分为下图所示的步骤。

圈组.png

第一步:集成 SDK

各端 SDK 的集成请参考相关集成文档。

第二步:初始化 SDK

各端 SDK 的集成请参考相关集成文档。

第三步:用户登录

登录 IM

客户端用户在使用网易云信即时通讯功能前需要先登录网易云信 IM 服务器。

建议参考 IM 登录最佳实践 实现 IM 登录以及相应的上层应用逻辑。

调用 login 方法进行登录。以静态 Token 登录为例,示例代码如下:

Android
JavaNIMClient.getService(V2NIMLoginService.class).login("account", "token", null, new V2NIMSuccessCallback<Void>() {
    @Override
    public void onSuccess(Void unused) {
        // TODO
    }
},
    new V2NIMFailureCallback() {
    @Override
    public void onFailure(V2NIMError error) {
        int code = error.getCode();
        String desc = error.getDesc();
        // TODO
    }
});
iOS
Objective-C- (void)login
{
    NSString *accountId = @"accountId";
    NSString *token = @"token";
    [[NIMSDK sharedSDK].v2LoginService login:accountId token:token
            option:nil
                success:^{
        NSLog(@"login succ");
    }
                failure:^(V2NIMError * _Nonnull error) {
        NSLog(@"login fail: error = %@", error);
    }];
}
macOS/Windows
C++V2NIMLoginOption option;
loginService.login(
    "accountId",
    "token",
    option,
    []() {
        // login succeeded
    },
    [](V2NIMError error) {
        // login failed, handle error
    });
Web/uni-app/小程序
TypeScripttry {
    await nim1.V2NIMLoginService.login("ACCOUNT_ID", "TOKEN", {
    "forceMode": false
    })
} catch (err) {
    // TODO failed, check code
    // console.log(err.code)
}
Node.js/Electron
TypeScriptawait v2.loginService.login('accountId', 'token', {})
HarmonyOS
TypeScripttry {
await nim.loginService.login("ACCOUNT_ID", "TOKEN", {
    forceMode: false
} as V2NIMLoginOption)
} catch (err) {
// TODO failed, check code
// console.log(err.code)
}
Flutter
dartfinal loginResult = await NimCore.instance.loginService.login(
    "ACCOUNT_ID", "TOKEN", NIMLoginOption());

其他登录方式请参考 登录登出 IM

登录聊天室

  1. 发送方和接收方调用 newInstance 方法创建聊天室实例。调用成功后,返回聊天室实例(instanceId),聊天室实例与聊天室(roomId)形成一一绑定关系。

    示例代码如下:

    Android
    JavaV2NIMChatroomClient chatroomClient = V2NIMChatroomClient.newInstance();
    
    iOS
    Objective-CV2NIMChatroomClient *chatroomClient = [V2NIMChatroomClient newInstance];
    
    macOS/Windows
    C++auto chatroomClient = V2NIMChatroomClient::newInstance();
    if (!chatroomClient) {
        // create instance failed
        // ...
        return;
    }
    auto instanceId = chatroomClient->getInstanceId();
    // save instanceId to cache
    // ...
    
    Web/uni-app/小程序
    TypeScriptconst chatroom = V2NIMChatroomClient.newInstance(
        {
            appkey: 'YOUR_APPKEY'
        }
    )
    
    Node.js/Electron
    TypeScriptconst chatroomClient = V2NIMChatroomClient.newInstance()
    
    HarmonyOS
    TypeScriptconst context: common.Context = getContext(this).getApplicationContext()
    const chatroom = V2NIMChatroomClient.newInstance(context,
        {
            appkey: 'YOUR_APPKEY'
        }
    )
    
  2. 发送方和接收方调用 addChatroomClientListener 方法注册聊天室登录相关监听器,包括聊天室连接状态变更、进出聊天室、被踢出聊天室。

    示例代码如下:

    Android
    JavachatroomClient.addChatroomClientListener(new V2NIMChatroomClientListener() {
        @Override
        public void onChatroomStatus(V2NIMChatroomStatus status, V2NIMError error) {
    
        }
    
        @Override
        public void onChatroomEntered() {
    
        }
    
        @Override
        public void onChatroomExited(V2NIMError error) {
    
        }
    
        @Override
        public void onChatroomKicked(V2NIMChatroomKickedInfo kickedInfo) {
    
        }
    });
    
    iOS
    Objective-C@interface ClientListener : NSObject <V2NIMChatroomClientListener>
    - (void)addToClient:(NSInteger)clientId;
    @end
    
    @implementation ClientListener
    - (void)addToClient:(NSInteger)clientId
    {
        V2NIMChatroomClient *instance = [V2NIMChatroomClient getInstance:clientId];
        [instance addChatroomClientListener:self];
    }
    
    - (void)onChatroomStatus:(V2NIMChatroomStatus)status
                    error:(nullable V2NIMError *)error
    {
    
    }
    - (void)onChatroomEntered
    {
    
    }
    
    - (void)onChatroomExited:(nullable V2NIMError *)error
    {
    
    }
    
    - (void)onChatroomKicked:(V2NIMChatroomKickedInfo *)kickedInfo
    {
    
    }
    @end
    
    macOS/Windows
    C++V2NIMChatroomClientListener listener;
    listener.onChatroomStatus = [](V2NIMChatroomStatus status, nstd::optional<V2NIMError> error) {
        // handle chatroom status
    };
    listener.onChatroomEntered = []() {
        // handle chatroom entered
    };
    listener.onChatroomExited = [](nstd::optional<V2NIMError> error) {
    // handle chatroom exited
    };
    listener.onChatroomKicked = [](V2NIMChatroomKickedInfo kickedInfo) {
        // handle chatroom kicked
    };
    chatroomClient.addChatroomClientListener(listener);
    
    Web/uni-app/小程序
    TypeScriptchatroom.on("onChatroomStatus", function (status: V2NIMChatroomStatus, err?: V2NIMError) {})
    chatroom.on("onChatroomEntered", function () {})
    chatroom.on("onChatroomExited", function (err?: V2NIMError) {})
    chatroom.on("onChatroomKicked", function (kickedInfo: V2NIMChatroomKickedInfo) {})
    
    Node.js/Electron
    TypeScriptchatroom.on("chatroomStatus", function (status: V2NIMChatroomStatus, err?: V2NIMError) {})
    chatroom.on("chatroomEntered", function () {})
    chatroom.on("chatroomExited", function (err?: V2NIMError) {})
    chatroom.on("chatroomKicked", function (kickedInfo: V2NIMChatroomKickedInfo) {})    
    
    HarmonyOS
    TypeScriptconst chatroom = this.getInstance(instanceId)
    chatroom.on("onChatroomStatus", (status: V2NIMChatroomStatus, err?: V2NIMError) => {
    })
    chatroom.on("onChatroomEntered", ()=> {
    })
    chatroom.on("onChatroomExited", (err?: V2NIMError) => {
    })
    chatroom.on("onChatroomKicked", (kickedInfo: V2NIMChatroomKickedInfo)=> {
    })
    
  3. 在登录聊天室之前,需要先提前获取聊天室地址。可以通过以下两种方式获取:

    • 若当前客户端已 登录 IM,那么可以通过 getChatroomLinkAddress 方法获取指定聊天室的地址。

      示例代码如下:

      Android
      JavaNIMClient.getService(V2NIMLoginService.class).getChatroomLinkAddress("123", new V2NIMSuccessCallback<List<String>>() {
                  @Override
                  public void onSuccess(List<String> result) {
                      // get success
                  }
              }, new V2NIMFailureCallback() {
                  @Override
                  public void onFailure(V2NIMError error) {
                      // get failed
                  }
              });
      
      iOS
      Objective-CNSString *roomId = @"36";
      [NIMSDK.sharedSDK.v2LoginService getChatroomLinkAddress:roomId
                                                      success:^(NSArray<NSString *> *links) {
                                                          // get success
                                                      }
                                                      failure:^(V2NIMError *error) {
                                                          // get failed
                                                      }];
      
      macOS/Windows
      C++loginService.getChatroomLinkAddress(
          "roomId",
          [](nstd::vector<nstd::string> linkAddresses) {
              // handle link addresses
          },
          [](V2NIMError error) {
              // handle error
          });
      
      Web/uni-app/小程序
      TypeScriptconst addressArray = await nim.V2NIMLoginService.getChatroomLinkAddress('36', isMiniApp)
      
      Node.js/Electron
      TypeScriptconst linkAddresses = await v2.loginService.getChatroomLinkAddress('roomId')
      
    • 若当前客户端未登录 IM,那么 SDK 无法获取聊天室服务器的地址,需要客户端向开发者应用服务器请求该地址,而应用服务器需要向网易云信服务器请求,然后将请求结果原路返回给客户端。具体请参考 获取聊天室地址 服务端 API。

  4. 发送方和接收方调用 enter 方法登录聊天室。以静态 Token 登录为例,示例代码如下:

    Android
    Java//创建 V2NIMChatroomClient(注意:不要每次都 newInstance,用完不再使用需要 destroyInstance)
    V2NIMChatroomClient chatroomClient = V2NIMChatroomClient.newInstance();
    //获取 chatroomClient 的实例 ID,可以缓存起来,后面通过 instanceId 可以得到 V2NIMChatroomClient
    int instanceId = chatroomClient.getInstanceId()
    
    ……
    
    V2NIMChatroomLinkProvider chatroomLinkProvider = new V2NIMChatroomLinkProvider() {
        @Override
        public List<String> getLinkAddress(String roomId, String accountId) {
            return "聊天室 Link 地址";
        }
    };
    V2NIMChatroomEnterParams enterParams = V2NIMChatroomEnterParams.V2NIMChatroomEnterParamsBuilder.builder(chatroomLinkProvider)
    .withAccountId("账号名")
    .withToken("静态 token")
    // 按需设置
    //.withRoomNick("进入聊天室后显示的昵称")
    //.withRoomAvatar("进入聊天室后显示的头像")
    //.withTimeout("进入方法超时时间")
    //.withServerExtension("用户扩展字段")
    //.withNotificationExtension("通知扩展字段,进入聊天室通知开发者扩展字段")
    //.withTagConfig("进入聊天室标签信息配置")
    //.withLocationConfig("进入聊天室空间位置信息配置")
    //.withAntispamConfig("用户资料反垃圾检测配置");
    .build();
    
    V2NIMChatroomClient chatroomClient = V2NIMChatroomClient.getInstance(instanceId);
    if(chatroomClient != null){
        chatroomClient.enter(roomId, enterParams,
            new V2NIMSuccessCallback<V2NIMChatroomEnterResult>() {
                @Override
                public void onSuccess(V2NIMChatroomEnterResult result) {
                    //进入成功
                }
            },
            new V2NIMFailureCallback() {
                @Override
                public void onFailure(V2NIMError error) {
                    //进入失败
                }
            });
    }
    
    iOS
    Objective-C@interface V2NIMEnterChatroom: NSObject <V2NIMChatroomLinkProvider>
    @end
    @implementation V2NIMEnterChatroom
    - (void)enter
    {
    NSString *roomId = @"36";
    //创建 V2NIMChatroomClient(注意:不要每次都 newInstance,用完不再使用需要 destroyInstance)
    V2NIMChatroomClient *client = [V2NIMChatroomClient newInstance];
    //获取 chatroomClient 的实例 ID,可以缓存起来,后面通过 instanceId 可以得到 V2NIMChatroomClient
    NSInteger instanceId = client.getInstanceId;
    
    V2NIMChatroomEnterParams *enterParams = [[V2NIMChatroomEnterParams alloc] init];
    enterParams.linkProvider = self;
    enterParams.accountId = @"账号名";
    enterParams.token = @"静态 token";
    // 按需设置
    // enterParams.roomNick: 进入聊天室后显示的昵称
    // enterParams.roomAvatar: 进入聊天室后显示的头像
    // enterParams.timeout: 进入方法超时时间
    // enterParams.serverExtension: 用户扩展字段
    // enterParams.notificationExtension: 通知扩展字段,进入聊天室通知开发者扩展字段
    // enterParams.tagConfig: 进入聊天室标签信息配置
    // enterParams.locationConfig: 进入聊天室空间位置信息配置
    // enterParams.antispamConfig: 用户资料反垃圾检测配置
    
    V2NIMChatroomClient *chatroomClient = [V2NIMChatroomClient getInstance:instanceId];
    [chatroomClient enter:roomId
            enterParams:enterParams
                success:^(V2NIMChatroomEnterResult *result)
                {
                    //进入成功
                }
                failure:^(V2NIMError *error)
                {
                        //进入失败
                }];
    }
    
    - (nullable NSArray<NSString *> *)getLinkAddress:(NSString *)roomId
                                        accountId:(NSString *)accountId
    {
        return @[@"聊天室 Link 地址"];
    }
    @end
    
    macOS/Windows
    C++V2NIMChatroomEnterParams enterParams;
    enterParams.accountId = "accountId";
    enterParams.token = "token";
    enterParams.roomNick = "nick";
    enterParams.roomAvatar = "avatar";
    enterParams.linkProvider = [](nstd::string roomId, nstd::string account) {
        nstd::vector<nstd::string> linkAddresses;
        // get link addresses
        // ...
        return linkAddresses;
    };
    enterParams.serverExtension = "server extension";
    enterParams.notificationExtension = "notification extension";
    chatroomClient.enter(
        "roomId",
        enterParams,
        [](V2NIMChatroomEnterResult result) {
            // enter succeeded
        },
        [](V2NIMError error) {
            // enter failed, handle error
        });
    
    Web/uni-app/小程序
    TypeScripttry {
        const chatroom = V2NIMChatroomClient.newInstance({
        appkey: 'YOUR_APPKEY',
        debugLevel: 'debug'
        })
        await chatroom.enter('YOUR_ROOM_ID', {
            accountId: 'YOUR_ACCOUNT_ID',
            token: 'YOUR_TOKEN'
        })
    } catch (err) {
        // TODO failed, check code
        // console.log(err.code)
    }
    
    Node.js/Electron
    TypeScriptconst result = await chatroomClient.enter('your room id', {
        accountId: 'your account id',
        token: 'your token',
        roomNick: 'your room nick',
        linkProvider: (roomId, account) => {
            return ['chatroom link...']
        }
    })
    if (result) {
        console.error(result)
    }
    
    HarmonyOS
    TypeScripttry {
        const chatroom = V2NIMChatroomClient.newInstance({
        appkey: 'YOUR_APPKEY',
        debugLevel: 'debug'
        })
        await chatroom.enter('YOUR_ROOM_ID', {
            accountId: 'YOUR_ACCOUNT_ID',
            token: 'YOUR_TOKEN'
        })
    } catch (err) {
        // TODO failed, check code
        // console.log(err.code)
    }
    
  5. 登录聊天室成功后,调用 getChatroomService 方法获取聊天室服务。后续聊天室相关操作(聊天室成员、消息等)均在返回的 Service 类中实现。

    Web/uni-app/小程序可跳过此步骤。

    示例代码如下:

    Android
    JavaV2NIMChatroomService chatroomService = chatroomClient.getChatroomService()
    
    iOS
    Objective-C[[V2NIMChatroomClient getInstance:instanceId] getChatroomService];
    
    macOS/Windows
    C++auto& chatroomService = client.getChatroomService();
    
    Node.js/Electron
    TypeScriptconst chatroomService = chatroomClient.getChatroomService()
    
    HarmonyOS
    TypeScriptconst client: V2NIMChatroomClient = this.getInstance(instanceId)
    const ret = client.chatroomService
    

登录圈组

NIM SDK V10 已采用融合登录方案,用户只需要调用 login 方法登录一次,则可以同时使用 IM 与圈组,无需再单独登录圈组服务器。具体示例代码请参考 登录 IM

调用 login 后调用 QChatService#login 方法将会报错。

第四步:收发消息

单聊/群聊收发消息

本节以发送发和接收方的消息交互为例,介绍快速实现单聊收发消息的流程。更多消息类型的收发,请参考 收发消息

创建或加入群组 后,用户发送和接收消息的接口与单聊收发消息相同,区别在于会话类型的参数配置,TEAM 为高级群,SUPER_TEAM 为超大群。

  1. 接收方调用 addMessageListener 方法注册消息监听器,监听消息接收回调事件 onReceiveMessages。示例代码如下:

    Android
    JavaV2NIMMessageService v2MessageService = NIMClient.getService(V2NIMMessageService.class);
    
    V2NIMMessageListener messageListener = new V2NIMMessageListener() {
    
        @Override
        public void onReceiveMessages(List<V2NIMMessage> messages) {
    
        }
    };
    v2MessageService.addMessageListener(messageListener);
    
    iOS
    Objective-C[[[NIMSDK sharedSDK] v2MessageService] addMessageListener:listener];
    
    macOS/Windows
    C++V2NIMMessageListener listener;
    listener.onReceiveMessages = [](nstd::vector<V2NIMMessage> messages) {
        // receive messages
    };
    messageService.addMessageListener(listener);
    
    Web/uni-app/小程序
    TypeScriptnim.V2NIMMessageService.on("onReceiveMessages", function (messages: V2NIMMessage[]) {})
    
    Node.js/Electron
    TypeScriptv2.messageService.on("receiveMessages", function (messages: V2NIMMessage[]) {})
    
    HarmonyOS
    TypeScriptnim.messageService.on("onReceiveMessages", function (messages: V2NIMMessage[]) {})
    
    Flutter
    dartsubsriptions.add(
        NimCore.instance.messageService.onReceiveMessages.listen((event) {
    //do something
    }));
    
  2. 发送方调用 createTextMessage 方法构建文本消息,然后调用 sendMessage 方法向接收方发送文本消息。示例代码如下:

    Android
    JavaV2NIMMessageService v2MessageService = NIMClient.getService(V2NIMMessageService.class);
    // 创建一条文本消息
    V2NIMMessage v2Message = V2NIMMessageCreator.createTextMessage("xxx");
    // 以单聊类型为例
    String conversationId = V2NIMConversationIdUtil.conversationId("xxx", V2NIMConversationType.V2NIM_CONVERSATION_TYPE_P2P);
    // 根据实际情况配置
    V2NIMMessageAntispamConfig antispamConfig = V2NIMMessageAntispamConfig.V2NIMMessageAntispamConfigBuilder.builder()
    .withAntispamBusinessId()
    .withAntispamCheating()
    .withAntispamCustomMessage()
    .withAntispamEnabled()
    .withAntispamExtension()
    .build();
    
    // 根据实际情况配置
    V2NIMMessageConfig messageConfig = V2NIMMessageConfig.V2NIMMessageConfigBuilder.builder()
    .withLastMessageUpdateEnabled()
    .withHistoryEnabled()
    .withOfflineEnabled()
    .withOnlineSyncEnabled()
    .withReadReceiptEnabled()
    .withRoamingEnabled()
    .withUnreadEnabled()
    .build();
    // 根据实际情况配置
    V2NIMMessagePushConfig pushConfig = V2NIMMessagePushConfig.V2NIMMessagePushConfigBuilder.builder()
    .withContent()
    .withForcePush()
    .withForcePushAccountIds()
    .withForcePushContent()
    .withPayload()
    .withPushEnabled()
    .withPushNickEnabled()
    .build();
    // 根据实际情况配置
    V2NIMMessageRobotConfig robotConfig = V2NIMMessageRobotConfig.V2NIMMessageRobotConfigBuilder.builder()
    .withAccountId()
    .withCustomContent()
    .withFunction()
    .withTopic()
    .build();
    // 根据实际情况配置
    V2NIMMessageRouteConfig routeConfig = V2NIMMessageRouteConfig.V2NIMMessageRouteConfigBuilder.builder()
    .withRouteEnabled()
    .withRouteEnvironment()
    .build();
    // 根据实际情况配置
    V2NIMSendMessageParams sendMessageParams = V2NIMSendMessageParams.V2NIMSendMessageParamsBuilder.builder()
    .withAntispamConfig(antispamConfig)
    .withClientAntispamEnabled()
    .withClientAntispamReplace()
    .withMessageConfig(messageConfig)
    .withPushConfig(pushConfig)
    .withRobotConfig(robotConfig)
    .withRouteConfig(routeConfig)
    .build();
    // 发送消息
    v2MessageService.sendMessage(v2Message, conversationId, sendMessageParams,
    new V2NIMSuccessCallback<V2NIMSendMessageResult>() {
        @Override
        public void onSuccess(V2NIMSendMessageResult v2NIMSendMessageResult) {
            // TODO: 发送成功
        },
        new V2NIMFailureCallback() {
            @Override
            public void onFailure(V2NIMError error) {
                // TODO: 发送失败
            }
        });
    }
    
    iOS
    Objective-C// 创建一条文本消息
    V2NIMMessage *message = [V2NIMMessageCreator createTextMessage:@"v2 message"];
    V2NIMSendMessageParams *params = [[V2NIMSendMessageParams alloc] init];
    // 发送消息
    [[[NIMSDK sharedSDK] v2MessageService] sendMessage:message
                                        conversationId:@"conversationId"
                                                params:params
                                            success:^(V2NIMSendMessageResult * _Nonull result) {
                                                // 发送成功回调
                                                }
                                            failure:^(V2NIMError * _Nonnull error) {
                                                // 发送失败回调,error 包含错误原因
                                                }
    }];
    
    macOS/Windows
    C++// 以单聊类型为例
    auto conversationId = V2NIMConversationIdUtil::p2pConversationId("target_account_id");
    // 创建一条文本消息
    auto message = V2NIMMessageCreator::createTextMessage("hello world");
    auto params = V2NIMSendMessageParams();
    // 发送消息
    messageService.sendMessage(
        message,
        conversationId,
        params,
        [](V2NIMSendMessageResult result) {
            // send message succeeded
        },
        [](V2NIMError error) {
            // send message failed, handle error
        });
    
    Web/uni-app/小程序
    TypeScripttry {
    // 创建一条文本消息
    const message: V2NIMMessage = nim.V2NIMMessageCreator.createTextMessage("hello")
    // 发送消息
    const res: V2NIMSendMessageResult = await nim.V2NIMMessageService.sendMessage(message, 'test1|1|test2')
    // Update UI with success message.
    } catch (err) {
    // todo error
    }
    
    Node.js/Electron
    TypeScriptconst message = v2.messageCreator.createTextMessage('Hello NTES IM')
    const result = await v2.messageService.sendMessage(message, conversationId, params, progressCallback)
    
    HarmonyOS
    TypeScripttry {
    // 创建一条文本消息
    const message: V2NIMMessage = nim.messageCreator.createTextMessage("hello")
    // 发送消息
    const res: V2NIMSendMessageResult = await nim.messageService.sendMessage(message, 'test1|1|test2')
    // todo Success
    } catch (err) {
    // todo error
    }
    
    Flutter
    dartawait MessageCreator.createTextMessage(text);
    await NimCore.instance.messageService.sendMessage(message, conversationId, params);
    

    目前 NIM SDK 支持多种消息类型,包括文本消息、图片消息、语音消息、视频消息、文件消息、地理位置消息、提示消息、通知消息以及自定义消息。具体请参考 收发消息

  3. 接收方通过 onReceiveMessages 回调收到文本消息。

聊天室收发消息

本节以发送方与接收方的消息交互为例,介绍通过 NIM SDK 快速实现聊天室收发消息的流程。

其他类型收发消息相关详情,请参考 聊天室消息管理

  1. 接收方注册聊天室监听器,监听聊天室消息接收回调事件 onReceiveMessages

    示例代码如下:

    Android
    JavaV2NIMChatroomClient v2ChatroomClient = V2NIMChatroomClient.getInstance(instanceId);
    V2NIMChatroomService v2ChatroomService = v2ChatroomClient.getChatroomService();
    
    V2NIMChatroomListener listener = new V2NIMChatroomListener() {
        @Override
        public void onReceiveMessages(List<V2NIMChatroomMessage> messages) {
    
        }
    };
    
    v2ChatroomService.addChatroomListener(listener);
    
    iOS
    Objective-C@interface Listener: NSObject<V2NIMChatroomListener>
    - (void)addToService;
    @end
    
    @implementation Listener
    
    - (void)addToService
    {
        id <V2NIMChatroomService> service = [[V2NIMChatroomClient getInstance:1] getChatroomService];
        [service addChatroomListener:self];
    }
    
    - (void)onReceiveMessages:(NSArray *)messages
    {
    
    }
    @end
    
    macOS/Windows
    C++V2NIMChatroomListener listener;
    listener.onReceiveMessages = [](nstd::vector<V2NIMChatroomMessage> messages) {
        // handle receive messages
    };
    chatroomService.addChatroomListener(listener);
    
    Web/uni-app/小程序
    TypeScriptchatroom.V2NIMChatroomService.on('onReceiveMessages', function (messages: V2NIMChatroomMessage[]){})
    
    Node.js/Electron
    TypeScriptchatroom.chatroomService.on('receiveMessages', function (messages: V2NIMChatroomMessage[]){})
    
    HarmonyOS
    TypeScriptchatroom.chatroomService.on('onReceiveMessages', (messages: V2NIMChatroomMessage[]) => {})
    
  2. 发送方调用 createTextMessage 方法,构建一条文本消息。并调用 sendMessage 方法,发送已构建的文本消息。

    示例代码如下:

    Android
    Java// 新建一个聊天室实例,注意:每次 newInstance 都会返回一个新的实例,实际使用中请一个聊天室对应一个 V2NIMChatroomClient 实例,使用中需要临时缓存
    V2NIMChatroomClient v2ChatroomClient = V2NIMChatroomClient.newInstance();
    // 获取聊天室服务
    V2NIMChatroomService v2ChatroomService = v2ChatroomClient.getChatroomService();
    // 创建一条文本消息
    V2NIMChatroomMessage v2Message = V2NIMChatroomMessageCreator.createTextMessage("xxx");
    
    V2NIMChatroomMessageConfig messageConfig = new V2NIMChatroomMessageConfig();
    // 根据实际情况配置
    // 设置是否需要在服务端保存历史消息,默认 true
    // messageConfig.setHistoryEnabled(true);
    // 设置是否是高优先级消息,默认 false
    // messageConfig.setHighPriority(false);
    
    V2NIMMessageRouteConfig routeConfig = V2NIMMessageRouteConfig.V2NIMMessageRouteConfigBuilder.builder()
    // 根据实际情况配置
    // .withRouteEnabled()
    // .withRouteEnvironment()
    .build();
    
    V2NIMMessageAntispamConfig antispamConfig = V2NIMMessageAntispamConfig.V2NIMMessageAntispamConfigBuilder.builder()
    // 根据实际情况配置
    // .withAntispamBusinessId()
    // .withAntispamCheating()
    // .withAntispamCustomMessage()
    // .withAntispamEnabled()
    // .withAntispamExtension()
    .build();
    
    V2NIMSendChatroomMessageParams params = new V2NIMSendChatroomMessageParams();
    // 设置消息相关配置
    // params.setMessageConfig(messageConfig);
    // 设置路由抄送相关配置
    // params.setRouteConfig(routeConfig);
    // 设置反垃圾相关配置
    // params.setAntispamConfig(antispamConfig);
    // 是否开启本地反垃圾,默认 false
    // params.setClientAntispamEnabled(false);
    // 本地反垃圾的替换文本
    // params.setClientAntispamReplace("xxx");
    //设置聊天室定向消息接收方账号 ID 列表
    // params.setReceiverIds(receiverIds);
    // 设置消息的目标标签表达式
    // params.setNotifyTargetTags("xxx");
    // 设置位置信息
    // params.setLocationInfo(locationInfo);
    v2ChatroomService.sendMessage(v2Message,params,
    new V2NIMSuccessCallback<V2NIMSendChatroomMessageResult>() {
        @Override
        public void onSuccess(V2NIMSendChatroomMessageResult result) {
            // 发送成功
        }
    },
    new V2NIMFailureCallback() {
        @Override
        public void onFailure(V2NIMError error) {
            // 发送失败
        }
    },
    new V2NIMProgressCallback() {
        @Override
        public void onProgress(int progress) {
            // 发送进度
        }
    });
    
    iOS
    Objective-C// 通过实例 ID 获取聊天室服务
    id <V2NIMChatroomService> service = [[V2NIMChatroomClient getInstance:instanceId] getChatroomService];
    // 创建一条文本消息
    V2NIMChatroomMessage *message = [V2NIMChatroomMessageCreator createTextMessage:@"xxx"];
    V2NIMChatroomMessageConfig *messageConfig = [V2NIMChatroomMessageConfig new];
    // 根据实际情况配置
    // 设置是否需要在服务端保存历史消息,默认 true
    // messageConfig.historyEnabled = YES;
    // 设置是否是高优先级消息,默认 false
    // messageConfig.highPriority = NO;
    V2NIMMessageRouteConfig *routeConfig = [V2NIMMessageRouteConfig new];
    // 根据实际情况配置
    // routeConfig.routeEnabled
    // routeConfig.routeEnvironment
    V2NIMMessageAntispamConfig *antispamConfig = [V2NIMMessageAntispamConfig new];
    // 根据实际情况配置
    // antispamConfig.antispamBusinessId
    // antispamConfig.antispamCheating
    // antispamConfig.antispamCustomMessage
    // antispamConfig.antispamEnabled
    // antispamConfig.antispamExtension
    
    V2NIMSendChatroomMessageParams *params = [V2NIMSendChatroomMessageParams new];
    // 设置消息相关配置
    // params.messageConfig = messageConfig;
    // 设置路由抄送相关配置
    // params.routeConfig = routeConfig;
    // 设置反垃圾相关配置
    // params.antispamConfig = antispamConfig;
    // 是否开启本地反垃圾,默认 false
    // params.clientAntispamEnabled = false;
    // 本地反垃圾的替换文本
    // params.clientAntispamReplace = @"xxx";
    // 设置聊天室定向消息接收方账号 ID 列表
    // params.receiverIds = receiverIds;
    // 设置消息的目标标签表达式
    // params.notifyTargetTags = @"xxx";
    // 设置位置信息
    // params.locationInfo = locationInfo;
    [service sendMessage:message
                params:params
                success:^(V2NIMSendChatroomMessageResult *result)
                {
                    // 发送成功
                }
                failure:^(V2NIMError *error)
                {
                    // 发送失败
                }
                progress:^(NSUInteger progress)
                {
                    // 上传进度
                }];
    
    macOS/Windows
    C++// 创建一条文本消息
    auto message = V2NIMChatroomMessageCreator::createTextMessage("hello world");
    auto params = V2NIMSendChatroomMessageParams();
    // 发送消息
    chatroomService.sendMessage(
        message,
        params,
        [](V2NIMSendChatroomMessageResult result) {
            // send message succeeded
        },
        [](V2NIMError error) {
            // send message failed, handle error
        },
        [](uint32_t progress) {
            // upload progress
        });
    
    Web/uni-app/小程序
    TypeScriptawait chatroom.V2NIMChatroomService.sendMessage(
        message,
        // V2NIMSendChatroomMessageParams
        {
            locationInfo: {x: 0, y: 100, z: 0}
        },
        progress: (percentage) => {console.log('上传进度: ' + percentage)}
    )
    
    Node.js/Electron
    TypeScriptconst message = V2NIMChatroomMessageCreator.createTextMessage('Hello NTES IM')
    await chatroomService.sendMessage(message, {})
    
    HarmonyOS
    TypeScript// 准备代发送的消息
    const msg: V2NIMChatroomMessage = this.chatroomClient.messageCreator.createTextMessage(text)
    // 发送聊天室消息时的参数
    const params: V2NIMSendChatroomMessageParams = {
    // 配置参数,如
    locationInfo: {x: 0, y: 100, z: 0}
    }
    // 发送进度回调,如上传附件时由该 cb 回调
    const progressCb = (percentage: number) => {
    this.messageSetProgress(imgMsg, percentage)
    console.info(`onUploadProgress: ${JSON.stringify(percentage)}`)
    }
    // send
    const msgRes: V2NIMSendChatroomMessageResult = await this.chatroomClient.chatroomService.sendMessage(msg, params, progressCb)
    
  3. 接收方通过 onReceiveMessages 回调收到聊天室消息。

圈组收发消息

圈组收发消息相关详情,请参考:

下一步

为保障通信安全,如果您在调试环境中的使用的是网易云信控制台生成的测试用 IM 账号 和 token,请确保在后续的正式生产环境中,将其替换为通过 IM 新版服务端 API 生成的正式 IM 账号和 token

涉及接口

Android/iOS/macOS/Windows
API 说明
addMessageListener 注册消息相关监听器
addChatroomClientListener 注册聊天室实例监听器
addChatroomListener 注册聊天室监听器
V2NIMLoginService.login 登录 IM
newInstance 构造聊天室实例
getChatroomLinkAddress 获取聊天室连接地址
enter 进入聊天室
getChatroomService 获取聊天室服务
V2NIMChatroomService 聊天室服务类
V2NIMConversationType 会话类型
V2NIMMessageCreator.createTextMessage 创建一条文本消息
V2NIMMessageService.sendMessage 发送消息
V2NIMChatroomMessageCreator.createTextMessage 创建一条聊天室文本消息
V2NIMChatroomService.sendMessage 发送聊天室消息
QChatService#login 登录圈组(旧接口)
Web/uni-app/小程序/Node.js/Electron/HarmonyOS
API 说明
V2NIMMessageService.on 注册消息相关监听器
V2NIMChatroomClient.on 注册聊天室实例监听器
V2NIMChatroomService.on 注册聊天室监听器
V2NIMLoginService.login 登录 IM
newInstance 构造聊天室实例
getChatroomLinkAddress 获取聊天室连接地址
enter 进入聊天室
getChatroomService 获取聊天室服务(除 Web 端)
V2NIMChatroomService 聊天室服务类
V2NIMConversationType 会话类型
V2NIMMessageCreator.createTextMessage 创建一条文本消息
V2NIMMessageService.sendMessage 发送消息
V2NIMChatroomMessageCreator.createTextMessage 创建一条聊天室文本消息
V2NIMChatroomService.sendMessage 发送聊天室消息
QChatService#login 登录圈组(旧接口)
Flutter
API 说明
NIMMessageService.add 注册消息相关监听器
NIMLoginService.login 登录 IM
NIMConversationType 会话类型
NIMMessageCreator.createTextMessage 创建一条文本消息
NIMMessageService.sendMessage 发送消息
QChatService#login 登录圈组(旧接口)
此文档是否对你有帮助?
有帮助
去反馈
  • 支持平台
  • 环境准备
  • 前提条件
  • 流程概览
  • 第一步:集成 SDK
  • 第二步:初始化 SDK
  • 第三步:用户登录
  • 登录 IM
  • 登录聊天室
  • 登录圈组
  • 第四步:收发消息
  • 单聊/群聊收发消息
  • 聊天室收发消息
  • 圈组收发消息
  • 下一步
  • 涉及接口