본문으로 바로가기
반응형

Spring에서 Websocket은 Spring 4부터 지원한다고 한다. 거기다 Java는 서버단의 언어로 사용되기 때문에 Websocket Clinet를 Java로 구현하는 것에 대한 예제가 많지 않다.

암호화폐 trading bot을 만들기 위해 spring boot로 websocket 요청을 할 필요가 있어서 이번 기회에 코드를 정리해 보았다.


사용한 라이브러리


Github에 올라와 있는 neovisionaries 라는 websocket 라이브러리를 사용하였다.

( https://github.com/TakahikoKawasaki/nv-websocket-client )



pom.xml


maven을 사용했기 때문에, pom.xml에 아래와 같은 dependency를 추가해 주었다. Gradle을 사용한다면 gradle에 추가해 주면 되겠다.

1
2
3
4
5
<dependency>
    <groupId>com.neovisionaries</groupId>
    <artifactId>nv-websocket-client</artifactId>
    <version>2.4</version>
</dependency>
cs



Source


간단하게 text를 입력받아 동일한 text를 return 해주는 테스트용 websocket 서버로 연결하는 소스 예제이다.


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
86
87
88
89
90
91
92
93
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketAdapter;
import com.neovisionaries.ws.client.WebSocketException;
import com.neovisionaries.ws.client.WebSocketExtension;
import com.neovisionaries.ws.client.WebSocketFactory;
 
 
public class EchoClient
{
    /**
     * The echo server on websocket.org.
     */
    private static final String SERVER = "ws://echo.websocket.org";
 
    /**
     * The timeout value in milliseconds for socket connection.
     */
    private static final int TIMEOUT = 5000;
 
 
    /**
     * The entry point of this command line application.
     */
    public static void main(String[] args) throws Exception
    {
        // Connect to the echo server.
        WebSocket ws = connect();
 
        // The standard input via BufferedReader.
        BufferedReader in = getInput();
 
        // A text read from the standard input.
        String text;
 
        // Read lines until "exit" is entered.
        while ((text = in.readLine()) != null)
        {
            // If the input string is "exit".
            if (text.equals("exit"))
            {
                // Finish this application.
                break;
            }
 
            // Send the text to the server.
            ws.sendText(text);
        }
 
        // Close the WebSocket.
        ws.disconnect();
    }
 
 
    /**
     * Connect to the server.
     */
    private static WebSocket connect() throws IOException, WebSocketException
    {
        System.out.println("Start get data from upbit");
        return new WebSocketFactory()
            .setConnectionTimeout(TIMEOUT)
            .createSocket(SERVER)
            .addListener(new WebSocketAdapter() {
                
                // binary message arrived from the server
                public void onBinaryMessage(WebSocket websocket, byte[] binary) {
                    String str = new String(binary);
                    System.out.println(str);
                }
                // A text message arrived from the server.
                public void onTextMessage(WebSocket websocket, String message) {
                    System.out.println(message);
                }
            })
            .addExtension(WebSocketExtension.PERMESSAGE_DEFLATE)
            .connect();
    }
 
 
    /**
     * Wrap the standard input with BufferedReader.
     */
    private static BufferedReader getInput() throws IOException
    {
        return new BufferedReader(new InputStreamReader(System.in));
    }
}
cs



Lessoned learn


웹소캣 서버에서 응답을 주는 형식을 잘 파악해야 onTextMessage만 connect method에 선언할 경우, 바이너리 배열 형식으로 리턴 오는 데이터는 수신 자체가 안 된다. 잘 모르겠으면 onTextMessage와 onBinaryMessage 양쪽을 다 열어서 확인해 보자.



반응형

 Other Contents