Spring Boot webSocket应用例子

[b]Spring Boot webSocket应用例子[/b]


[b]后端代码:[/b]
<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") // 扫描那些包得到bean.@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 {
// 接收消息处理
@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();// 关闭连接
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

// 新的WebSocket请求开启
@OnOpen
public void onOpen(Session session) {
System.out.println("webSocket onOpen");
}

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

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



[b]前端代码:[/b]
<!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);

//产生异常
webSocket.onerror = function (event) {
onError(event)
};

//已经建立连接
webSocket.onopen = function (event) {
onOpen(event)
};

//收到服务器消息,使用evt.data提取
webSocket.onmessage = function (event) {
onMessage(event)
};

//已经关闭连接
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);
//收到服务器消息,使用evt.data提取
webSocket.onmessage = function (event) {
alert("onmessage");
onMessage(event)
};
}
}

window.onbeforeunload = function () {
alert("onbeforeunload");
webSocket.send('close'); //发送关闭请求让服务器关闭链接
webSocket.close();//关闭TCP连接
webSocket = null;
return false; // 可以阻止关闭
}
</script>
</body>
</html>



参考:[url]http://zk-chs.iteye.com/blog/2285329[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值