Home react stompjs
Post
Cancel

react stompjs

리액트와 스프링의 소켓 통신을 위한 stompjs 사용

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import logo from './logo.svg';
import './App.css';
import React, { useEffect, useState } from 'react';
import * as StompJS from '@stomp/stompjs';
import styled from 'styled-components';

const AppStyle = styled.div`
  padding: 100px;
  display: flex;
  flex-direction: column;
  align-items: center;

  textarea {
    margin: 10px;
    width: 400px;
    height: 300px;
  }
`;

const client = new StompJS.Client({
  brokerURL: 'ws://localhost:8001',
  connectHeaders: {
    login: 'user',
    passcode: 'password',
  },
  debug: function (str) {
    console.log('debug', str);
  },
  //요청 딜레이
  //500
  reconnectDelay: 5000,
  // 핸드셰이크 후 어느 시점에서든 클라이언트 또는 서버가 상대방에게 핑(ping) 을 보낼 수 있습니다.
  // 핑이 수신되면 수신자는 가능한 한 빨리 퐁(pong) 을 보내야합니다.
  // 이게 바로 허트비트(heartbeat) 입니다. 이 도구를 사용하여 클라이언트가 계속 연결되어 있는지 확인할 수 있습니다.
  //400
  heartbeatIncoming: 4000,
  heartbeatOutgoing: 4000,
});
function App() {
  const [text, setText] = useState('');
  useEffect(() => {
    //연결
    client.onConnect = function (frame) {
      //서버 -> 클라이언트로 메세지 받는 부분
      //생성할때 client.subscribe로 받을 url 여러개 만듬
      client.subscribe('/message', function (message) {
        console.log(JSON.parse(message.body));
      });
      client.subscribe('/room', function (message) {
        console.log(JSON.parse(message.body));
      });
    };
    //에러
    client.onStompError = function (frame) {
      console.log('Broker reported error: ' + frame.headers['message']);
      console.log('Additional details: ' + frame.body);
    };
    //활성화
    client.activate();
  }, []);

  //중지
  const deactivate = () => {
    client.deactivate();
  };
  //보내기
  const send = () => {
    client.publish({
      destination: '/aaa',
      body: JSON.stringify({ message: text }),
      headers: { 'content-type': 'application/json' },
    });
  };

  return (
    <AppStyle>
      <textarea />
      <input value={text} onChange={(e) => setText(e.target.value)}></input>
      <button onClick={send}>sendMessage</button>
      <button onClick={deactivate}>연결중지</button>
    </AppStyle>
  );
}

export default App;

node로는 테스트 해봤지만 spring에서 작동되는지 확인 하지 못함.

테스트 보류중

This post is licensed under CC BY 4.0 by the author.