编写自己的聊天网站(一)

编写自己的聊天网站(一)

欢迎大家加我微信交流技术—xy1399666

后端实现技术(springboot+websocket+security)

前言:第一次写,有不到之处请提出意见,希望我们一起进步。
1.首先当然是创建一个springboot项目,相信这个大家应该都没什么问题哈,然后是引入websocket和security的jar包啦。当然后面还要连接数据库的mybtis-jar包,这些基础的就不贴出来了

     <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId><version>2.1.8.RELEASE</version></dependency>

2.写个WebSocket配置类WebSocketConfig

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {//注册STOMP协议的节点@Overridepublic void registerStompEndpoints(StompEndpointRegistry registry) {//映射指定的 URL,指定使用SockJS协议registry.addEndpoint("/endpointWisely").withSockJS();  //注册STOMP协议的节点endpoint,并指定SockJS协议// 1  注册一个新的endpointregistry.addEndpoint("/endpointChat").withSockJS();}//配置消息代理@Overridepublic void configureMessageBroker(MessageBrokerRegistry registry) {//广播式应该配置一个topic代理registry.enableSimpleBroker("/queue","/topic");}
}

3.接下来在配置一下Security(WebSecurityConfig)

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@AutowiredDaouser dao;@AutowiredDataSource dataSource;@Overrideprotected void configure(HttpSecurity httpSecurity) throws Exception {httpSecurity.authorizeRequests()//1    对/  和  /login  路径不拦截.antMatchers("/","/login").permitAll().anyRequest().authenticated().and().formLogin()//2    设置登录页面的路径.loginPage("/login")//3     成功后跳转至fchat路径.defaultSuccessUrl("/fchat").permitAll().and().logout().permitAll();}//4  在内存中配置两个用户名、密码、角色,定义认证用于信息获取来源以及密码校验规则//认证信息获取来源是内存获取——inMemoryAuthentication@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception{//代码报错  There is no PasswordEncoder mapped for the id “null”//https://blog.csdn.net/canon_in_d_major/article/details/79675033//Spring security 5.0中新增了多种加密方式,也改变了密码的格式//要将前端传过来的密码进行某种方式加密,spring security 官方推荐的是使用bcrypt加密方式//基于内存存储用户信息auth.userDetailsService(new WebSecuritylet());auth.inMemoryAuthentication().withUser("liuyishou").password("123456").roles("USER").and().withUser("wangdefa").password("123456").roles("USER");}}//5  指定路径下的静态资源不拦截@Overridepublic void configure(WebSecurity webSecurity) throws Exception{webSecurity.ignoring().antMatchers("/resources/static/**");}}

(4) 控制器示例

@Controller
public class WsController {//1 通过SimpMessagingTemplate 向浏览器发送消息@Autowiredprivate SimpMessagingTemplate messagingTemplate;@MessageMapping("/chat")public void handleChat(Principal principal, String msg){  //2   springMVC 中可以直接在参数中获取principal,它包含了当前用户的信息//3  如果发送人是mmz,则发送给wisely,暂时硬编码测试,生产中看情况if(principal.getName().equals("gdg")){//4 向用户发送消息,convertAndSendToUser(接收消息的用户,浏览器的订阅地址,消息体)messagingTemplate.convertAndSendToUser("yq","/queue/notifications",principal.getName() + "-send:" + msg);}else {messagingTemplate.convertAndSendToUser("gdg","/queue/notifications",principal.getName() + "-send:" + msg);}}

(5) 登录页面 在src/main/resources/templates下新建 login.html,

<!DOCTYPE html>
<html lang="zh-CN"xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/xhtml"xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<head><title>登陆页面</title>
</head>
<body>
<div th:if="${param.error}">无效的账号和密码
</div>
<div th:if="${param.logout}">你已注销
</div>
<form th:action="@{/login}" method="post"><div><label> 账号 : <input type="text" name="username"/> </label></div><div><label> 密码: <input type="password" name="password"/> </label></div><div><input type="submit" value="登陆"/></div>
</form>
</body>
</html>

(6)聊天页面 在src/main/resources/templates下新建 chat.html,

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<head><title>Home</title><!--<script th:src="@{/https://code.jquery.com/jquery-3.4.1.min.js}" type="text/javascript"></script>--><script th:src="@{/static/jquery-3.3.1.js}" type="text/javascript"></script><script th:src="@{/static/sockjs.min.js}" type="text/javascript"></script><script th:src="@{/static/stomp.min.js}" type="text/javascript"></script>
</head>
<body>
<p>聊天室
</p><form id="wiselyForm"><textarea rows="4" cols="60" name="text"></textarea><input type="submit"/>
</form><script th:inline="javascript">$('#wiselyForm').submit(function(e){e.preventDefault();var text = $('#wiselyForm').find('textarea[name="text"]').val();sendSpittle(text);});var sock = new SockJS("/endpointChat"); //1  连接endpointvar stomp = Stomp.over(sock);stomp.connect('guest', 'guest', function(frame) {//2    订阅 /user/queue/notifications 发送的消息,要求与messagingTemplate 中定义的地址一样,多了个user,且是必须的,这样才能把消息发送到指定的用户stomp.subscribe("/user/queue/notifications", handleNotification);});function handleNotification(message) {$('#output').append("<b>Received: " + message.body + "</b><br/>")}function sendSpittle(text) {stomp.send("/chat", {}, text);//3}$('#stop').click(function() {sock.close()});
</script><div id="output"></div>
</body>
</html>

(7)增加页面的viewController

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {@Overridepublic void addViewControllers(ViewControllerRegistry registry){//访问localhost:8787/ws  跳转ws.html页面registry.addViewController("/ws").setViewName("/ws");registry.addViewController("/login").setViewName("/login");registry.addViewController("/chat").setViewName("/chat");}/*** 自动配置静态资源*/@Overrideprotected void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/static/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX + "/static/");super.addResourceHandlers(registry);}}

ps:打开两个浏览器窗口,谷歌浏览器可设置两个独立用户,然后访问http://localhost:8085/login
登录 liuyishou/123456,wangdefa/123456 ,然后就可以刘一手和王德发实时通信了。

最后:当然这只是最简单的例子:后面还有实现类似微信网页版的功能 ,登录注册-好友列表-群聊-添加好友一系列的功能

编写自己的聊天网站(一)相关推荐

  1. JAVA WEB快速入门之从编写一个JSP WEB网站了解JSP WEB网站的基本结构、调试、部署...

    接上篇<JAVA WEB快速入门之环境搭建>,在完成了环境搭建后(JDK.Tomcat.IDE),现在是万事具备,就差写代码了,今天就来从编写一个JSP WEB网站了解JSP WEB网站的 ...

  2. java8生成jsp页面内容组装到jsp中_JAVA WEB快速入门之从编写一个JSP WEB网站了解JSP WEB网站的基本结构、调试、部署...

    接上篇<JAVA WEB快速入门之环境搭建>,在完成了环境搭建后(JDK.Tomcat.IDE),现在是万事具备,就差写代码了,今天就来从编写一个JSP WEB网站了解JSP WEB网站的 ...

  3. TcpClient和TcpListener 类的使用-编写一个点对点聊天工具(初级入门篇)

    TcpClient类和TcpListener类属于.NET框架下网络通信中的应用层类,为Socket通信提供了更简单,对用户更为友好的接口.应用层类比位于底层的Socket类提供了更高层次的抽象,封装 ...

  4. 最新在线客服系统php代码微信软件公众号小程序app二维码聊天网站源码

    最新在线客服系统php代码微信软件公众号小程序app二维码聊天网站源码 管理界面 独家长期更新日志(欢迎反馈BUG) 1.添加手机端前后台声音提示 2.添加后台客户管理显示在线离线 3.添加清空当前对 ...

  5. Java爬虫之利用Jsoup+HttpClient爬取类叔叔不约匿名聊天网站的图片,未果——后爬取某网站美女图片案例

    博主最近学了一点爬虫的知识,闲着无聊,秉承学以致用的理念,于是突然想到何不挑战一下,爬取一些叔叔不约网站的图片,来巩固一下所学知识(#滑稽).说干就干,打开eclipse或idea,创建maven工程 ...

  6. 自己动手用Android和Xposed编写一个微信聊天机器人——《微信聊天精灵》实现关键词自动回复。

    出于爱好和需要,想着自己来编写一个微信聊天机器人,能实现以下功能: 能实时获取到微信聊天消息: 能进行文本自动回复: 能够设置关键词: 能够根据关键词匹配,进行内容回复: 能实现聊天消息云端备份: 已 ...

  7. 视频聊天网站的研究、发展以及趋势时间

    摘要: 此文讲述了视频聊天网站相关的技术.发展过程以及未来的发展趋势.我长时间从事外包业务开发和技术开发的,从客户那里了解到了很多的视频聊天网站相关的需求,经过自己长时间对视频聊天网站运营模式.盈利模 ...

  8. 【转帖】视频聊天网站的研究、发展以及趋势

    摘要: 此文讲述了视频聊天网站相关的技术.发展过程以及未来的发展趋势.我长时间从事外包业务开发和技术开发的,从客户那里了解到了很多的视频聊天网站相关的需求,经过自己长时间对视频聊天网站运营模式.盈利模 ...

  9. 视频聊天网站的技术与发展

    视频聊天网站的技术与发展 摘要: 此文讲述了视频聊天网站相关的技术.发展过程.从客户那里了解到了很多的视频聊天相关的需求,经过自己长时间对视频聊天网站运营模式.盈利模式.系统架构以及相关技术的研究,写 ...

最新文章

  1. 35 线程优先级队列(queue)
  2. BeanUtils工具包操作JavaBean
  3. 超级实用sap table
  4. H5工程师在谷歌浏览器调试并开发原生APP项目的解决办法
  5. 企业开发--React 中的this使用
  6. vue极致打包_vue 各种打包坑
  7. getHibernateTemplate()(Spring中常用的hql查询方法)
  8. 区块链开发公司:区块链技术如何改变个人数据安全
  9. ibavformat.so.57: cannot open shared object file: No such file or directory
  10. AD中批量导入域用户的命令
  11. VC++使用CImage在内存中Bmp转换Jpeg图片
  12. C#仿““狗屁不通文章生成器””功能
  13. 【windows】修复win7便签
  14. 基于javaweb+springboot的电影售票系统(java+Springboot+ssm+mysql+jsp+maven)
  15. PHP实现讯飞语音转写demo
  16. Stimulsoft Reports 综合平台2019.x-2020.x
  17. 中文依存句法结构分析
  18. 题解 2020级HAUT新生周赛(二)
  19. 8.2 知识蒸馏方法概述
  20. laravel安装 nwidart/laravel-modules 出现的问题

热门文章

  1. 华为鸿蒙内存机制,华为鸿蒙系统对内存有要求吗?
  2. win10安装win7虚拟机记录
  3. LeetCode: 173. Binary Search Tree Iterator
  4. 备份恢复Lesson 07. lmproving Your Backups
  5. Python爬虫实战,QQ音乐爬取全部歌曲
  6. Altium Designer 2020 学习笔记(一)-----原理图及原理图库部分(配动态图操作演示)
  7. 秀出新天际的SpringBoot笔记,让开发像搭积木一样简单
  8. 计算机工作表中按升序排列,计算机文化基础上机指导
  9. 帕慕克给我上的一堂编程学习课
  10. redis 的incr 高并发 原子性计数器