Spring Boot webSocket application example

Spring Boot webSocket application example


backend code:
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>



package com.cesmart;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@EnableAutoConfiguration
@ComponentScan(basePackages = "com.cesmart") // scan those packages for beans.@ComponentScan({"com.teradata.notification","com.teradata.dal"})
public class Application {
	public static void main(String[] args) {
		ApplicationContext applicationContext = SpringApplication.run(Application.class, args);
	}
}



package com.cesmart.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter (){
        return new ServerEndpointExporter();
    }
}



package com.cesmart.controller;

import java.io.IOException;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

@ServerEndpoint("/WebSocketTest")
@Component
public class WebSocketTest {
	// receive message processing
	@OnMessage
	public void onMessage(Session session, String message) {
		System.out.println("webSocket onMessage message == " + message);
		if (session != null) {
			try {
				session.getBasicRemote().sendText("Server Test!<br>");
			} catch (IOException e) {
				e.printStackTrace ();
			}
		} else {
			System.out.println("this.session == null");
		}

		if (message.equals("close")) {
			System.out.println("this.session message == close");
			try {
				session.close();//Close the connection
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace ();
			}
		}

	}

	// open a new WebSocket request
	@OnOpen
	public void onOpen(Session session) {
		System.out.println("webSocket onOpen");
	}

	// WebSocket request close
	@OnClose
	public void onClose(Session session) {
		System.out.println("webSocket onClose");
		if (session != null) {
			try {
				session.close();
			} catch (IOException e) {
				e.printStackTrace ();
			}
		}
	}

	// WebSocket error
	@OnError
	public void onError(Throwable thr) {
		System.out.println("onError");
		thr.printStackTrace();
	}
}



Front-end code:
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>websocketTest</title>
</head>
<body>
<div>
    <input type="button" value="connect" onclick="connectfn()"/>
</div>
<div>
    <input type="button" value="Start" onclick="start()"/>
</div>
<div>
    <input type="button" value="close" onclick="closefn()"/>
</div>
<div id="messages"></div>
<script type="text/javascript">
    var testUrl = 'ws: //127.0.0.1: 8090 / WebSocketTest';
    var webSocket =
            new WebSocket(testUrl);

    // generate exception
    webSocket.onerror = function (event) {
        onError(event)
    };

    //The connection has been established
    webSocket.onopen = function (event) {
        onOpen(event)
    };

    //Receive server message, use evt.data to extract
    webSocket.onmessage = function (event) {
        onMessage(event)
    };

    //The connection has been closed
    webSocket.onclose = function (event) {
        alert("onclose");
        webSocket.close();
    };

    function onMessage(event) {
        document.getElementById('messages').innerHTML
                += '<br />' + event.data;
    }

    function onOpen(event) {
        alert("onOpen");
        document.getElementById('messages').innerHTML
                = 'Connection established';
    }

    function onError(event) {
        alert(event.data);
    }

    function start() {
        alert("start");
        webSocket.send('hello');
        //return false;
    }

    function closefn() {
        alert("close");
        webSocket.send('close');
        webSocket.close();
        webSocket = null;
    }
    function connectfn() {
        alert("connectfn");
        if (webSocket == null) {
            alert("webSocket == null");
            webSocket =
                    new WebSocket(testUrl);
            //Receive server message, use evt.data to extract
            webSocket.onmessage = function (event) {
                alert("onmessage");
                onMessage(event)
            };
        }
    }

    window.onbeforeunload = function () {
        alert("onbeforeunload");
        webSocket.send('close'); //Send a close request to let the server close the connection
        webSocket.close();//Close the TCP connection
        webSocket = null;
        return false; // can prevent closing
    }
</script>
</body>
</html>



Reference: http://zk-chs.iteye.com/blog/2285329

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326896704&siteId=291194637