构建高性能的WebSocket

构建背景

SpringBoot作为最近比较主流的开发框架,可以使开发者快速、优雅的创建应用。结合最近公司小伙伴对WebSocket提及的次数暴增,因此介绍一下如何使用SpringBoot + Netty快速构建的WebSocket项目。

创建SpringBoot项目

可以在SpringBoot快速的初始化一个SpringBoot项目,启动器仅选择Web即可;
网站截图

添加依赖

添加Netty-WebSocket的依赖项并等待IDE加载完成对应的包;

<dependency>
	<groupId>org.yeauty</groupId>
	<artifactId>netty-websocket-spring-boot-starter</artifactId>
	<version>0.6.2</version>
</dependency>

配置服务发布Bean

需要添加对服务发布用到的类进行配置,配置如下:

@Configuration
public class WebSocketConfiguration
{
	@Bean
	public ServerEndpointExporter serverEndpointExporter()
	{
		ServerEndpointExporter exporter = new ServerEndpointExporter();
		return exporter;
	}
}

创建WebSocket消息监听处理类

最后,我们需要创建一个用于接收请求和处理请求的类,该类的作用相当于一个Controller:

@ServerEndpoint
@Component
public class WebSocketServer
{
	
	@OnOpen
	public void onOpen(Session session, HttpHeaders headers)
	{
		//TODO
		System.out.println("Connected..");
	}
	
	@OnClose
	public void onClose(Session session)
	{
		//TODO
		System.out.println("DisConnected..");
	}
	
	
	@OnError
	public void onError(Session session, Throwable exception)
	{
		//TODO
		exception.printStackTrace();
	}
	
	@OnMessage
	public void OnMessage(Session session, String message)
	{
		//TODO
		System.out.println("Message Receive & Send Method..");
	}
}

创建消息页面

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8"/>
	<title>WebSocket测试</title>
</head>
<body>
	<div id="msg"></div>
	<input type="text" id="text">
	<input type="submit" value="send" onclick="send()">
</body>
<script type="text/javascript">
		var msg = document.getElementById("msg");
		var wsServer = 'ws://127.0.0.1:80';
		var websocket = new WebSocket(wsServer);
		//监听连接打开
		websocket.onopen = function (evt) {
			msg.innerHTML = "The connection is open";
		};
		//监听服务器数据推送
		websocket.onmessage = function (evt) {
			msg.innerHTML += "<br>" + evt.data;
		};
		//监听连接关闭
		websocket.onclose = function (evt) {
			console.info("连接已关闭...");
		};
		function send() {
			var text = document.getElementById("text").value;
			websocket.send(text);
		}
	</script>
</html>

测试

最后,运行SringBoot项目(既打开WebSocket服务),打开对应的HTML页面,完成请求的测试即可。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值