SpringBoot-2.X 学习笔记08 整合WebSocket

1 在 SpringBoot 中加入依赖。

1 在 SpringBoot 的 pom.xml 中加入依赖包

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

2 在 SpringBoot 增加一个配置。

package com.xu.springboot.websocket;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig extends SpringBootServletInitializer {

	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
		return application.sources(WebSocketConfig.class);
	}

	@Bean
	public TaskScheduler taskScheduler(){
		ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
		taskScheduler.setPoolSize(10);
		taskScheduler.initialize();
		return taskScheduler;
	}

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

}

3 在增加一个 WebSocket 消息发送工具类。

package com.xu.springboot.websocket;

import java.io.IOException;
import java.util.Map;

import javax.websocket.Session;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class WebSocketUtils {

	static Log log=LogFactory.getLog(WebSocketUtils.class);
	
	public static void send_single_message(Session session,String message) {
		try {
			session.getBasicRemote().sendText(message);
		} catch (IOException e) {
			log.info(e);
		}
	}

	public static void send_mutils_message(Map<String, Session> map,String msg) {
		map.forEach((k,v)->{try {
			v.getBasicRemote().sendText(msg);
		} catch (IOException e) {
			log.info(e);
		}});
	}

}

4 WebSocket 测试类。

4.1 Java类

package com.xu.springboot.websocket;

import java.io.IOException;
import java.util.Map;

import javax.websocket.Session;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class WebSocketUtils {

	static Log log=LogFactory.getLog(WebSocketUtils.class);
	
	public static void send_single_message(Session session,String message) {
		try {
			session.getBasicRemote().sendText(message);
		} catch (IOException e) {
			log.info(e);
		}
	}

	public static void send_mutils_message(Map<String, Session> map,String msg) {
		map.forEach((k,v)->{try {
			v.getBasicRemote().sendText(msg);
		} catch (IOException e) {
			log.info(e);
		}});
	}

}

4.2 HTML页面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	自己:<input type="text" id="me" name="me" value="001" />
	<br /> 
	别人:<input type="text" id="username" name="username" value="002" />
	<br /> 
	信息:<input type="text" id="msg" name="msg" />
	<br />
	<input type="button" value="ReFresh" onclick="msg()" />
	<br />
</body>
<script type="text/javascript">
	function msg() {
		var socket;
		if (typeof (WebSocket) == "undefined") {
			console.log("您的浏览器不支持WebSocket");
		} else {
			console.log("您的浏览器支持WebSocket");
			//实现化WebSocket对象,指定要连接的服务器地址与端口  建立连接
			index = new WebSocket("ws://localhost:8080/socket/{"+document.getElementById("me").value+"}/{"+document.getElementById("username").value+"}/{"+document.getElementById("msg").value+"}");
			//socket = new WebSocket("${basePath}websocket/${cid}".replace("http","ws"));
			//打开事件
			index.onopen = function() {
				console.log("Socket 已打开");
				//socket.send("这是来自客户端的消息" + location.href + new Date());
			};
			
			//获得消息事件
			index.onmessage = function(msg) {
				console.log(msg.data);
				document.getElementById("msg").value = msg.data;
			};
			//关闭事件
			index.onclose = function() {
				console.log("Socket已关闭");
			};
			//发生了错误事件
			index.onerror = function() {
				alert("Socket发生了错误");
			}
		}
	}
</script>
</html>

5 结果

结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值