`
huangyongxing310
  • 浏览: 490546 次
  • 性别: Icon_minigender_1
  • 来自: 广州
文章分类
社区版块
存档分类
最新评论

Spring Boot webSocket应用例子

阅读更多
Spring Boot webSocket应用例子


后端代码:
<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();
	}
}



前端代码:
<!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>




netty实现websocket
https://blog.csdn.net/weixin_39168678/article/details/79453585
https://www.cnblogs.com/chaizezhao/articles/5291608.html
https://www.cnblogs.com/ggwow/p/7994213.html
https://www.cnblogs.com/tohxyblog/p/7771200.html
https://www.cnblogs.com/tohxyblog/p/7946498.html
https://www.cnblogs.com/wunaozai/p/5240006.html
https://www.jianshu.com/p/568a1a6ff17e
https://blog.csdn.net/weixin_39168678/article/details/79453585

https://blog.csdn.net/xieliaowa9231/article/details/80151446(springboot整合netty做websocket服务器)
http://www.cnblogs.com/duanxz/archive/2013/12/11/3468972.html(Netty实现简单HTTP服务器)
https://blog.csdn.net/qq_36994771/article/details/80085876(springboot整合netty 使用WebSocket进行不同房间多人聊天)




参考:http://zk-chs.iteye.com/blog/2285329
分享到:
评论

相关推荐

    spring boot websocket例子

    spring boot websocket例子,实现socket连接,关闭,发送消息功能,运行Application.java运行项目,访问地址http://localhost:8080/socket.html

    spring boot+websocket前后端简单demo

    在本文中,我们将深入探讨如何使用Spring Boot和WebSocket技术创建一个简单的前后端交互示例。...通过这个示例,开发者可以进一步了解WebSocket在实时应用中的作用,以及如何将其集成到Spring Boot项目中。

    spring-boot-websocket-client代码示例

    在本文中,我们将深入探讨如何使用Spring Boot构建一个WebSocket客户端。`spring-boot-websocket-client`这个项目就是一...通过学习这个示例,开发者可以更好地理解和应用WebSocket技术在Spring Boot项目中的实际运用。

    spring boot websocket , mongoDBd存文件 图片服务器

    在本文中,我们将深入探讨如何使用Spring Boot构建一个WebSocket服务器,并与MongoDB集成,特别是利用GridFS存储文件,包括图片。此外,我们还将讨论非GridFS的文件存储方式及其限制。 首先,Spring Boot是一个简化...

    SpringWebSocket-master.zip

    SpringWebSocket-master.zip是一个包含Spring Boot应用的示例项目,展示了如何使用WebSocket技术和STOMP协议实现前后端通信。WebSocket是一种在单个TCP连接上进行全双工通信的协议,相较于传统的HTTP请求,它允许...

    spring-boot-websocket.rar

    2. **WebSocket Controller**:Spring Boot应用中可能会有一个WebSocket控制器,它处理WebSocket连接的建立、消息的发送和接收。控制器类可能包含`@MessageMapping`注解的方法,这些方法对应WebSocket的消息路由。 ...

    Spring Boot 2 Cookbook 第二版

    《Spring Boot 2 Cookbook 第二版》是一本针对Java开发者极具价值的开发指南,它深入浅出地介绍了Spring Boot ...书中的例子和实践指导将帮助你更好地理解和应用Spring Boot 2的各种特性,从而提高开发效率和代码质量。

    spring集成webSocket

    Spring 框架为开发者提供了便捷地集成 WebSocket 的功能,下面将详细介绍 Spring 如何集成 WebSocket 及其实现站内消息实时推送。 1. **配置WebSocket支持** - 引入依赖:Spring Boot 的 WebSocket 支持通常需要 `...

    springWebsocket的简单例子

    在本文中,我们将深入探讨如何使用Spring框架,特别是Spring WebSocket,来创建一个简单的WebSocket应用程序。这对于初学者来说是一个很好的起点,因为它提供了一个直观的理解和实践机会。 首先,让我们了解Spring ...

    spring websocket在线聊天demo

    总之,"spring websocket在线聊天demo"是一个展示如何利用Spring集成WebSocket技术创建实时聊天应用的例子。它涉及到WebSocket的配置、Stomp协议的应用、前后端交互以及聊天功能的实现,为开发者提供了构建此类应用...

    spring-boot 各种demo例子(最新)

    "spring-boot 各种demo例子(最新)" 提供的是最新的 Spring Boot 集成示例代码,可以帮助开发者快速理解和学习如何在实际项目中应用 Spring Boot。下面我们将深入探讨这些 demo 示例中可能包含的关键知识点: 1. **...

    springcloud实现gate网关转发功能和整合websocket源码

    在Spring Boot中,我们可以使用`@ServerEndpoint`注解来创建WebSocket端点,如下所示: ```java import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax...

    使用Spring Boot + WebSocket 构建的一个简易聊天室

    在本文中,我们将深入探讨如何使用Spring Boot和WebSocket技术构建一个简易的聊天室。Spring Boot是Java领域中广泛使用的框架,它简化了Spring应用程序的初始设置和配置。WebSocket则是一种在客户端和服务器之间建立...

    Spring Boot 集成 WebSocket 实现服务端推送消息到客户端.docx

    Spring Boot 提供了对 WebSocket 的集成支持,使得在 Java 后端实现 WebSocket 功能变得简单。首先,我们需要在 `pom.xml` 文件中引入 Spring Boot 的 WebSocket 依赖: ```xml &lt;groupId&gt;org.springframework....

    Spring-Boot-Jetty-WebSocket-Example:如何使用Spring Boot配置Jetty WebSocket的基本示例

    在本文中,我们将深入探讨如何使用Spring Boot与Jetty服务器集成来实现WebSocket通信。WebSocket是一种在客户端和服务器之间...通过深入学习和实践这个例子,你可以熟练掌握在Spring Boot应用中集成WebSocket的方法。

    spring boot入门例子

    Spring Boot 是一个由 Pivotal 团队开发的框架,旨在简化Spring应用的初始搭建以及开发过程。它集成了大量的常用第三方库配置,如数据源、JPA、定时任务、缓存、邮件服务等,使得开发者可以“零”配置启动项目,极大...

    Spring Websocket

    在Spring Boot项目中,可以通过在配置类上添加@EnableWebSocketMessageBroker注解来启用WebSocket消息代理。接着,可以重写WebSocketMessageBrokerConfigurer接口的方法,如configureMessageBroker和...

    Spring Boot技术知识点:Spring Boot2.7以上支持使用Swagger3

    Spring Boot 是一个流行的Java开发框架,它简化了创建独立、生产级别的基于Spring的应用程序。随着版本的升级,Spring Boot引入了对新特性和工具的支持。在Spring Boot 2.7及以上版本,它开始支持Swagger 3,这是一...

    spring-websocket实时统计报表示例

    在Spring Boot应用中,你可以通过定义一个`@Controller`类并使用`@MessageMapping`注解来创建WebSocket端点。例如: ```java import org.springframework.messaging.handler.annotation.MessageMapping; import org...

    Websocket简单示例(Spring Boot)

    在本示例中,我们将探讨如何在Spring Boot框架下实现WebSocket,以便创建实时、双向通信的应用。 首先,我们需要在Spring Boot项目中添加WebSocket的相关依赖。在`pom.xml`文件中,引入`spring-boot-starter-...

Global site tag (gtag.js) - Google Analytics