java spring 웹소켓 > 질문답변

본문 바로가기
사이트 내 전체검색

질문답변

java spring 웹소켓

페이지 정보

profile_image
작성자 미친새
댓글 0건 조회 21,311회 작성일 20-02-21 12:23

본문

1. Spring 4.x, WebSocket

# pom.xml

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-websocket</artifactId>
    <version>4.2.1.RELEASE</version>
</dependency>


# servlet-context.xml

<websocket:handlers>

    <websocket:mapping handler="webSocketHandler" path="/websocket" />

</websocket:handlers>



# WebSocketHandler.java

import org.springframework.web.socket.TextMessage;

import org.springframework.web.socket.WebSocketSession;

import org.springframework.web.socket.handler.TextWebSocketHandler;



public class WebSocketHandler extends TextWebSocketHandler {

    @Override

    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

        for (int i = 0; i < 10; i++) {

            session.sendMessage(new TextMessage(message.getPayload()));

            Thread.sleep(1000);

        }

    }


}



# websocket.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript" src="/resources/js/jquery/jquery-1.11.3.min.js"></script>



<script type="text/javascript">

var ws = new WebSocket('ws://localhost:8080/websocket');

ws.onopen = function() {

    $('#console').append('websocket opened' + '<br>');

};

ws.onmessage = function(message) {

    $('#console').append('receive message : ' + message.data + '<br>');

};

ws.onclose = function(event) {

    $('#console').append('websocket closed : ' + event);

};


function messageSend() {

    ws.send($('#message').val());

}

</script>

</head>

<body>



<input type="text" id="message" />

<input type="button" value="전송" onclick="messageSend();" />

<div id="console" />



</body>

</html>



2. Spring 4.x, SockJS

# 다운로드

- SockJS 다운로드 : https://github.com/sockjs/sockjs-client/tree/master/dist

 

# pom.xml

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-websocket</artifactId>
    <version>4.2.1.RELEASEversion>
</dependency>
 

# servlet-context.xml

<websocket:handlers>

    <websocket:mapping handler="webSocketHandler" path="/websocket" />

    <websocket:sockjs />

</websocket:handlers>



# WebSocketHandler.java

import org.springframework.web.socket.TextMessage;

import org.springframework.web.socket.WebSocketSession;

import org.springframework.web.socket.handler.TextWebSocketHandler;



public class WebSocketHandler extends TextWebSocketHandler {

    @Override

    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

        for (int i = 0; i < 10; i++) {

            session.sendMessage(new TextMessage(message.getPayload()));

            Thread.sleep(1000);

        }

    }


}



# websocket.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript" src="/resources/js/jquery/jquery-1.11.3.min.js"></script>

<script type="text/javascript" src="/resources/js/sockjs/sockjs-1.0.3.min.js"></script>



<script type="text/javascript">

var sock = new SockJS('http://localhost:8080/websocket');

sock.onopen = function() {

    $('#console').append('websocket opened' + '<br>');

};

sock.onmessage = function(message) {

    $('#console').append('receive message : ' + message.data + '<br>');

};

sock.onclose = function(event) {

    $('#console').append('websocket closed : ' + event);

};


function messageSend() {

    sock.send($('#message').val());

}

</script>

</head>

<body>



<input type="text" id="message" />

<input type="button" value="전송" onclick="messageSend();" />

<div id="console" />



</body>

</html>



3. Srping 4.x, SockJS, STOMP

# 다운로드

- SockJS 다운로드 : https://github.com/sockjs/sockjs-client/tree/master/dist

- STOMP 다운로드 : http://jmesnil.net/stomp-websocket/doc/

 

# pom.xml

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-websocket</artifactId>
    <version>4.2.1.RELEASEversion>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-messaging</artifactId>
    <version>4.2.1.RELEASE</version>
</dependency>
 

# servlet-context.xml

<websocket:message-broker application-destination-prefix="/app">

    <websocket:stomp-endpoint path="/stomp">

        <websocket:sockjs />

    </websocket:stomp-endpoint>

    <websocket:simple-broker prefix="/topic" />

</websocket:message-broker>



# WebSocketController.java

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.messaging.handler.annotation.MessageMapping;

import org.springframework.messaging.handler.annotation.SendTo;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;



@Controller

public class WebSocketController {


    @MessageMapping("/stomp")

    @SendTo("/topic/stomp")

    public ResponseEntity<String> stomp(String request) {

        return new ResponseEntity<String>(request, HttpStatus.OK);

    }


}



# websocket.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript" src="/resources/js/jquery/jquery-1.11.3.min.js"></script>

<script type="text/javascript" src="/resources/js/sockjs/sockjs-1.0.3.min.js"></script>

<script type="text/javascript" src="/resources/js/stomp/stomp.min.js"></script>



<script type="text/javascript">

    var socket = new SockJS('/stomp');

    var stompClient = Stomp.over(socket);

    stompClient.connect({}, function(frame) {

        $('#console').append('Connected: ' + frame + '<br>');

        stompClient.subscribe('/topic/stomp', function(message) {

            $('#console').append(message.body + '<br>');

        });

    });



    function disconnect() {

        if (stompClient != null) {

            stompClient.disconnect();

        }

        $('#console').append('Disconnected<br>');

    }

 

    function messageSend() {

        stompClient.send("/app/stomp", {}, $('#message').val());

    }

</script>

</head>

<body>



<input type="text" id="message" />

<input type="button" value="전송" onclick="messageSend();" />

<input type="button" value="종료" onclick="disconnect();" />

<div id="console" />



</body>

</html>



출처: http://sooin01.tistory.com/entry/Spring-WebSocket [수앙]

댓글목록

등록된 댓글이 없습니다.

회원로그인

회원가입

사이트 정보

회사명 : 회사명 / 대표 : 대표자명
주소 : OO도 OO시 OO구 OO동 123-45
사업자 등록번호 : 123-45-67890
전화 : 02-123-4567 팩스 : 02-123-4568
통신판매업신고번호 : 제 OO구 - 123호
개인정보관리책임자 : 정보책임자명

공지사항

  • 게시물이 없습니다.

접속자집계

오늘
1,766
어제
1,869
최대
5,296
전체
1,479,146
Copyright © 소유하신 도메인. All rights reserved.