# 채팅 메시지

채팅 메시지를 보내고 받기 위해서는 필요한 객체 선언과 채팅창기능들이 준비되어야 한다.
만약 준비가 되지 않았다면 생성하는 방법을 익히고 오도록 하자 준비사항 바로가기

# 메시지 전송

channel.sendMessage(
  {
    message: '전송될 메시지',
    mimeType: 'text',
  },
  function(err) {
    // 성공시에는 null, 오류시 err 객체 리턴 ({code: -1, type: "TIMEOUT", message: "Timed out after waiting 30000(ms) ..."})
    if (err) openError('메시지 전송을 실패하였습니다.');
  }
);
1
2
3
4
5
6
7
8
9
10
  • 파라미터 값

    식별자 설명
    message String 전송할 메시지
    mimeType String 메시지형태 (text: 일반텍스트, emoji: 이모지)
  • 결과 값

    식별자 설명
    code String 에러 코드
    message String 에러 메시지

# 프로젝트에 적용할 코드

    # 신규 메시지 이벤트

    channel.onNotifyMessage = function(event) {
      // {"nickName":"홍길동","roomId":"e7works","clientKey":"user고유키","message":"전송될 메시지","mimeType":"text","messageDt":"20200826160708","messageCount":4979,"grade":"user"}
      console.log(event);
    };
    
    1
    2
    3
    4
    • 푸시 결과 값

      식별자 설명
      nickName String 메시지를 전송한 채팅방 입장 유저의 별명
      roomId String 채팅방 생성 후 발급받은 Channel Key
      clientKey String 메시지를 전송한 접속 단말 설정 고유키
      message String 전송된 메시지
      mimeType String 메시지형태 (text: 일반텍스트, emoji: 이모지)
      messageDt String 전송 날짜
      messageCount String 채팅방 메시지 전송 수
      grade String 메시지를 전송한 유저의 등급 ( 사용자등급표 에서 확인 )

    # 프로젝트에 적용할 코드

    channel.onNotifyMessage = function(event) {
      write(event);
    };
    
    1
    2
    3

    # 특정 유저로 메시지를 전송

    channel.sendWhisper(
      {
        message: '전송될 메시지(귓말)',
        mimeType: 'text',
        receivedClientKey: 'user고유키',
      },
      function(err, msg) {
        if (err) {
          // 성공시에는 null, 오류시 err 객체 리턴 ({"code":10107,"type":"RECIPIENT_FAILURE","message":"USER_NOT_EXISTED"})
          return console.log(err);
        }
        // 성공시 객체 리턴 {"nickName":"vchat","roomId":"e7works","clientKey":"2a66d6a3","message":"안녕","receivedClientKey":"chatSample","mimeType":"text","messageDt":"20200831122540","messageCount":5852,"grade":"user","receivedNickName":"홍길동"}
        console.log(msg);
      }
    );
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    • 파라미터 값

      식별자 설명
      message String 전송할 메시지
      mimeType String 메시지 형태 (text: 일반텍스트, emoji: 이모지)
      receivedClientKey String 수신 유저의 접속 단말 설정 고유키
    • 결과 값

      • err
      식별자 설명
      code String 에러 코드
      message String 에러 메시지
      • msg
      식별자 설명
      roomId String 채팅방 생성 후 발급받은 Channel Key
      nickName String 채팅방 입장 유저의 별명
      clientKey String 메시지를 전송한 접속 단말 설정 고유키
      message Date 전송한 메시지
      mimeType String 메시지 형태 (text: 일반텍스트, emoji: 이모지)
      messageDt String 전송 날짜
      messageCount String 채팅방 메시지 전송 수
      receivedNickName String 메시지를 받는 유저의 별명
      receivedClientKey String 메시지를 받는 접속 단말 설정 고유키
      grade String 메시지를 전송한 유저의 등급 ( 사용자등급표 에서 확인 )

    # 프로젝트에 적용할 코드

    var popupLayer = $('div.popupLayer');
    var whisperLayer = $('ul.popup_content li:nth-child(1)', $('div.popupLayer'));
    popupLayer.close = function() {
      $('#whisper input[type=text][name=message]', whisperLayer).val('');
      $('#whisper', this).hide();
      $(this).hide();
    };
    $('button', whisperLayer).click(function(e) {
      channel.sendWhisper(
        {
          message: $('input[type=text][name=message]', whisperLayer).val(),
          receivedClientKey: popupLayer.data()['clientKey'],
        },
        function(err, msg) {
          if (err) return openError(err.message);
          write(msg, 'whisperto');
        }
      );
      e.preventDefault();
      popupLayer.close();
    });
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21

    # 개인 귓속말 메시지 이벤트

    channel.onPersonalWhisper = function(event) {
      // {"nickName":"홍길동","roomId":"e7works","clientKey":"user고유키","message":"전송될 메시지(귓말)","receivedClientKey":"user고유키","mimeType":"text","messageDt":"20200826160933","messageCount":4981,"grade":"user"}
      console.log('onPersonalWhisper', event);
    };
    
    1
    2
    3
    4
    • 푸시 결과 값

      식별자 설명
      roomId String 채팅방 생성 후 발급받은 Channel Key
      nickName String 채팅방 입장 유저의 별명
      clientKey String 메시지를 전송한 접속 단말 설정 고유키
      message Date 전송한 메시지
      mimeType String 메시지 형태 (text: 일반텍스트, emoji: 이모지)
      messageDt String 전송 날짜
      messageCount String 채팅방 메시지 전송 수
      receivedClientKey String 메시지를 받는 접속 단말 설정 고유키
      grade String 메시지를 전송한 유저의 등급 ( 사용자등급표 에서 확인 )

    # 프로젝트에 적용할 코드

    channel.onPersonalWhisper = function(event) {
      write(event, 'whisper');
    };
    
    1
    2
    3

    # 전체 코드

    메시지 이벤트 전체코드
    $(function() {
      // 입력창 엔터
      $('div.bottom div.emoji a').click(function() {
        channel.sendMessage({
          message: $(this).text(),
          mimeType: 'emoji',
        });
      });
      // 클릭 버튼
      $('#sendCounter').click(function(e) {
        channel.sendMessage({
          message: $('#content').text(),
          mimeType: 'text',
        });
        $('#content').text('');
      });
      // 이모지 버튼
      $('#content').keydown(function(e) {
        if (e.keyCode == 13) {
          e.preventDefault();
          channel.sendMessage({
            message: $(this).text(),
            mimeType: 'text',
          });
          $(this).text('');
        }
      });
      // 특정 유저로 메시지 전송
      var popupLayer = $('div.popupLayer');
      var whisperLayer = $('ul.popup_content li:nth-child(1)', $('div.popupLayer'));
      popupLayer.close = function() {
        $('#whisper input[type=text][name=message]', whisperLayer).val('');
        $('#whisper', this).hide();
        $(this).hide();
      };
      $('button', whisperLayer).click(function(e) {
        channel.sendWhisper(
          {
            message: $('input[type=text][name=message]', whisperLayer).val(),
            receivedClientKey: popupLayer.data()['clientKey'],
          },
          function(err, msg) {
            if (err) return openError(err.message);
            write(msg, 'whisperto');
          }
        );
        e.preventDefault();
        popupLayer.close();
      });
    });
    // chatInit() 부분은 login.js에 joinRoom 이 성공한 이후에 실행하도록 한다
    function chatInit() {
      // 신규 메시지 이벤트
      channel.onNotifyMessage = function(event) {
        write(event);
      };
      // 개인 귓속말 메시지 이벤트
      channel.onPersonalWhisper = function(event) {
        write(event, 'whisper');
      };
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    Copyright 2022. E7Works Inc. & JOYTUNE Corp. All Rights Reserved.