springboot2.0开发websocket应用完整示例 -欧洲杯足彩官网

`

springboot2.0开发websocket应用完整示例

环境说明:springboot版本2.0.3.release(不同版本可能有些差异),gradle版本4.5.1(这个版本不太关键)

  websocket是微信小程序的基础,是应用广泛、前景很好的新技术,目前大热。这里简要介绍一下使用springboot框架开发websocket应用的基础代码。基本原理不讲了,代码原理见函数注释,画个简单的图说明基本流程,如下图所示。




一、引用支撑包
    compile('org.springframework.boot:spring-boot-starter-websocket')

二、websocket服务端
package com.wallimn.iteye.sp.asset.bus.websocket;
import java.io.ioexception;
import java.util.concurrent.copyonwritearrayset;
import java.util.concurrent.atomic.atomicinteger;
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.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.stereotype.component;
/**
 * websocket服务端示例
 * @author wallimn,http://wallimn.iteye.com
 *
 */
@serverendpoint(value = "/ws/asset")
@component
public class websocketserver {
	private static logger log = loggerfactory.getlogger(websocketserver.class);
	private static final atomicinteger onlinecount = new atomicinteger(0);
	// concurrent包的线程安全set,用来存放每个客户端对应的session对象。
	private static copyonwritearrayset sessionset = new copyonwritearrayset();
	/**
	 * 连接建立成功调用的方法
	 */
	@onopen
	public void onopen(session session) {
		sessionset.add(session); 
		int cnt = onlinecount.incrementandget(); // 在线数加1
		log.info("有连接加入,当前连接数为:{}", cnt);
		sendmessage(session, "连接成功");
	}
	/**
	 * 连接关闭调用的方法
	 */
	@onclose
	public void onclose(session session) {
		sessionset.remove(session);
		int cnt = onlinecount.decrementandget();
		log.info("有连接关闭,当前连接数为:{}", cnt);
	}
	/**
	 * 收到客户端消息后调用的方法
	 * 
	 * @param message
	 *            客户端发送过来的消息
	 */
	@onmessage
	public void onmessage(string message, session session) {
		log.info("来自客户端的消息:{}",message);
		sendmessage(session, "收到消息,消息内容:" message);
	}
	/**
	 * 出现错误
	 * @param session
	 * @param error
	 */
	@onerror
	public void onerror(session session, throwable error) {
		log.error("发生错误:{},session id: {}",error.getmessage(),session.getid());
		error.printstacktrace();
	}
	/**
	 * 发送消息,实践表明,每次浏览器刷新,session会发生变化。
	 * @param session
	 * @param message
	 */
	public static void sendmessage(session session, string message) {
		try {
			session.getbasicremote().sendtext(string.format("%s (from server,session id=%s)",message,session.getid()));
		} catch (ioexception e) {
			log.error("发送消息出错:{}", e.getmessage());
			e.printstacktrace();
		}
	}
	/**
	 * 群发消息
	 * @param message
	 * @throws ioexception
	 */
	public static void broadcastinfo(string message) throws ioexception {
		for (session session : sessionset) {
			if(session.isopen()){
				sendmessage(session, message);
			}
		}
	}
	/**
	 * 指定session发送消息
	 * @param sessionid
	 * @param message
	 * @throws ioexception
	 */
	public static void sendmessage(string sessionid,string message) throws ioexception {
		session session = null;
		for (session s : sessionset) {
			if(s.getid().equals(sessionid)){
				session = s;
				break;
			}
		}
		if(session!=null){
			sendmessage(session, message);
		}
		else{
			log.warn("没有找到你指定id的会话:{}",sessionid);
		}
	}
	
}


三、服务端推送测试controller
    使用浏览器打开“/api/ws/sendone?message=单发消息内容&id=none”群发消息(需要根据实际情况修改id值,这个值见浏览器或ide控制台输出信息),“/api/ws/sendall?message=单发消息内容”单发消息。
package com.wallimn.iteye.sp.asset.bus.websocket;
import java.io.ioexception;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.bind.annotation.requestparam;
import org.springframework.web.bind.annotation.restcontroller;
/**
 * websocket服务器端推送消息示例controller
 * 
 * @author wallimn,http://wallimn.iteye.com
 *
 */
@restcontroller
@requestmapping("/api/ws")
public class websocketcontroller {
	@requestmapping(value="/sendall", method=requestmethod.get)
	/**
	 * 群发消息内容
	 * @param message
	 * @return
	 */
	string sendallmessage(@requestparam(required=true) string message){
		try {
			websocketserver.broadcastinfo(message);
		} catch (ioexception e) {
			e.printstacktrace();
		}
		return "ok";
	}
	@requestmapping(value="/sendone", method=requestmethod.get)
	/**
	 * 指定会话id发消息
	 * @param message 消息内容
	 * @param id 连接会话id
	 * @return
	 */
	string sendonemessage(@requestparam(required=true) string message,@requestparam(required=true) string id){
		try {
			websocketserver.sendmessage(id,message);
		} catch (ioexception e) {
			e.printstacktrace();
		}
		return "ok";
	}
}


四、页面端代码

websocket测试

	

websocket测试,在控制台查看测试信息输出!

http://wallimn.iteye.com

[url=/api/ws/sendone?message=单发消息内容&id=none]单发消息链接[/url] [url=/api/ws/sendall?message=群发消息内容]群发消息链接[/url]



问题补充:

一、如果希望打成war包,部署到tomcat中。需要使启动类继承:springbootservletinitializer,并加入方法:
/**
* 用于支持打包成war,部署到tomcat中。
*/
@override
protected springapplicationbuilder configure(springapplicationbuilder builder) {
return builder.sources(assetapplication.class);
}

二、如果打成war包后,在tomcat中启动时报错:multiple endpoints may not be deployed to the same path
注释掉websocketserver类上的@component注解。
  • 大小: 21.9 kb
  • (3 kb)
  • 描述: java及html源码
  • 下载次数: 321
2
1
分享到:
|
评论
4 楼 silence19841230 2018-10-24  
先拿走看看
3 楼 wallimn 2018-06-29  
masuweng 写道

发下源码下载地址吧!

三个相关文件打了个包,如果喜欢可以下载。
2 楼 masuweng 2018-06-29  

发下源码下载地址吧!
1 楼 masuweng 2018-06-28  
                

相关推荐

    通过springboot2.0整合websocket实现服务器主动推送消息到前端,并且前端接收到消息后会进行消息声音弹框提醒。

    springboot2.0 websocket的集成,实现群发消息 单对单消息推送.

    项目基于springboot2.0 项目实现了websocket点对点和广播两种方式。分别演示了http和ws两种不同协议下的请求。前端采用socketjs和stomp.js。主要提供了解决思路。需要的可以在此基础上进行延伸。

    主要介绍了springboot2.0整合websocket代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

    springboot2.0集成websocket,实现后台向前端推送信息

    springboot项目整合websocket netty实现前后端双向通信(同时支持前端websocket和socket协议哦) springboot项目整合websocket netty实现前后端双向通信(同时支持前端websocket和socket协议哦) springboot项目整合...

    java开发基于springboot websocket redis分布式即时通讯群聊系统。一个基于spring boot websocket redis,可快速开发的分布式即时通讯群聊系统。适用于直播间聊天、游戏内聊天、客服聊天等临时性群聊场景。 ...

    websocket为web应用程序提供了一种在单个tcp连接上进行全双工通信的方式。spring boot框架为开发者提供了集成websocket的便利性。本文将详细介绍如何在spring boot项目中设置和使用websocket。 websocket通信协议于...

    基于springboot2.0 vue的前后端分离系统权限架构,使用security控制权限,websocket实时聊天,vue编写前端,另包含可执行mysql脚本

    基于springboot websocket的简单聊天室 基于springboot websocket的简单聊天室 基于springboot websocket的简单聊天室 基于springboot websocket的简单聊天室 基于springboot websocket的简单聊天室 基于springboot ...

    springboot整合websocket

    应读者要求 写个了一个简单地springboot websocket实现进度条的demo。

    springboot整合websocket nacos注册中心实现多服务通信

    基于springboot2.0的开发的系统 易读易懂、界面简洁美观。 具备支付系统通用的支付、对账、清算、账户管理、支付订单管理等功能; 目前已接通微信支付渠道,应用微信公众号商城 在此基础上可二次开发,可以用于所有...

    springboot websocket广播式应用,使用idea ,其中包括单播,广播,多播

    springboot netty websocket redis 分布式聊天,实现简单的聊天功能

    基于springboot vue websocket的校园交友项目基于springboot vue websocket的校园交友项目基于springboot vue websocket的校园交友项目基于springboot vue websocket的校园交友项目基于springboot vue websocket的...

    局域网聊天工具基于springboot netty websocket,可发送图片表情包。

    springboot websocket 实例: 实时读取日志升级版(追加消息广播,清空日志通知重新连接)

global site tag (gtag.js) - google analytics
网站地图