미누에요

[Flutter] Socket_io 에러, ERROR [WsExceptionsHandler] Unexpected token o in JSON at position 1 본문

우당탕탕개발기록

[Flutter] Socket_io 에러, ERROR [WsExceptionsHandler] Unexpected token o in JSON at position 1

미누라니까요 2025. 2. 27. 19:41
728x90
반응형
SMALL

Flutter의 socket_io 를 사용하여 채팅 기능을 작업하던 중 ERROR [WsExceptionsHandler] Unexpected token o in JSON at position 1 이라는 에러가 발생하며 socket의 연결이 안되는 문제가 발생하였다.

 

Flutter 프론트 측에서는 socekt.connect로 요청을 보내도, socket이 disconnect를 보내서 연결이 되지 않았다.

서버 측의 로그를 확인해보니 아래와 같았다.

 

 

 

에러 로그를 보니 JSON으로 보낸 데이터의 형식이 맞지 않는다는 내용인 거 같았다.

그래서 코드들의 내용을 보니, 이벤트에 해당하는 데이터를 같이 보낼 , String 형식으로 보내지 않고 객체 형식으로 보내고 있다는 것을 깨댤았다.

 

void sendMessage(String sender, String type, String joinRoom, String content) {
    if (socket == null || !socket!.connected) {
        print("Socket is not connected. Unable to send message.");
        return;
}

 

socket!.emit('sendMessage', {
  'sender': sender,
  'type': type,
  'join_room': joinRoom,
  'content': content,
}));
}

 

그래서 .toString()을 사용하여 문자열 형식으로 다시 보냈다.

 

void sendMessage(String sender, String type, String joinRoom, String content) {
    if (socket == null || !socket!.connected) {
        print("Socket is not connected. Unable to send message.");
        return;
}

 

socket!.emit('sendMessage', {
  'sender': sender,
  'type': type,
  'join_room': joinRoom,
  'content': content,
}.toString());
}

 

근데 여전히 같은 문제가 발생하는것이다..............

그래서 헤메던 중 jsonEncode라는 함수를 찾았다.

 

 

void sendMessage(String sender, String type, String joinRoom, String content) {
    if (socket == null || !socket!.connected) {
        print("Socket is not connected. Unable to send message.");
        return;
}

 

socket!.emit('sendMessage', jsonEncode({
  'sender': sender,
  'type': type,
  'join_room': joinRoom,
  'content': content,
}));
}

 

이런 식으로 데이터를 보내자마자. 2일동안 나를 괴롭혔던 에러가 해결되었다...................

혹시 이벤트를 보낼 에러가 발생한다면............ jsonEncode() .........사용해보세요............

728x90
반응형
LIST