1、现在通过QQ、微信聊天已经非常普遍了,我们常用的网站中联系商家等也是链接到QQ中,一般不会自己去开发聊天模块,一来是因为浏览器权限有限,二来是安全性不高,开发一个完整系统的在线聊天难度系统也并不小。
但是也有些客户有这种网页单聊群聊的需求,我也就做了一个基于webSocket的网页在线聊天。
2、技术栈包括springboot+webSocket+Jquery,先展示一下效果。
3、接下来直接贴代码,贴一下结构图:
新建springboot项目后按照以下操作完成操作。
先导入Maven依赖:
org.springframework.boot
spring-boot-starter-websocket
org.projectlombok
lombok
4、新建WebSocketConfig 类,用来处理socket异常,必须要有,否则会显示找不到socket服务器404错误
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();
}
}
5、新建控制类WebSocketController,用来校验身份,我就没写实现了,跟我们今天做的关系不大。
import com.example.testchat2.server.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
@RestController
public class WebSocketController {
@Autowired
WebSocketServer server;
@PostMapping("/login")
public String login(String username,String password) throws IOException {
//TODO: 校验密码