只是个demo所以没有写任何样式,消息也没有做处理,只做了发送和接收以及显示,比较简单,可以用来当做参考
一 引入websocket.jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
二 注入WebSocketConfig
package com.example.demo.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();
}
}
三 编写WebSocket服务
package com.example.demo.server;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
@Slf4j
@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//接收sid
private String sid="";
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session, @PathParam("sid") String sid) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
this.sid=sid;
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("websocket IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到来自窗口"+sid+"的信息:"+message);
//群发消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群发自定义消息
* */
public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException {
log.info("推送消息到窗口"+sid+",推送内容:"+message);
for (WebSocketServer item : webSocketSet) {
try {
//这里可以设定只推送给这个sid的,为null则全部推送
if(sid==null) {
item.sendMessage(message);
}else if(item.sid.equals(sid)){
item.sendMessage(message);
}
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
四 编写Controller
package com.example.demo.controller;
import com.example.demo.server.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Slf4j
@Controller
public class IndexController {
/**
* 跳转登录页
* @return
*/
@RequestMapping("/index")
public String index(){
log.error("sssssssssssssssssssss");
return "index";
}
/**
* 跳转聊天页面
* @param id
* @param request
* @return
*/
@RequestMapping(value = "/login/{id}", method = RequestMethod.GET)
public String login(@PathVariable("id") int id, HttpServletRequest request){
request.getSession().setAttribute("id", id);
return "main";
}
/**
* 发送消息
* @param msg
* @param id
* @return
*/
@RequestMapping(value = "/send/{id}/{msg}", method = RequestMethod.POST)
@ResponseBody
public String send(@PathVariable("msg") String msg, @PathVariable("id") int id){
try{
// sid 为null 推送所有人 sid不为null时 推送给指定的 id
WebSocketServer.sendInfo(msg, null);
return "success";
}catch (Exception e){
log.error(e.getMessage());
return "faile";
}
}
}
五 编写网页
1 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<input id="id" type="text" placeholder="请输入id">
<button id="login" >登录</button>
</div>
</body>
<script src="/jquery.min.js"></script>
<script>
$(function () {
$("#login").click(function () {
var id = $("#id").val();
window.location.href= "/login/"+id;
})
})
</script>
</html>
2. main.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<input id="id" readonly value="${id}">
<div id="content" style="width: 800px; height: auto;border: solid;"></div>
<input id="text" type="text" placeholder="请输入内容">
<button id="send">发送</button>
</div>
</body>
</html>
<script src="/jquery.min.js"></script>
<script>
var id = $("#id").val();
var socket;
if (typeof(WebSocket) == "undefined"){
console.log("您的浏览器不支持WebSocket")
}else {
console.log("您的浏览器支持WebSocket")
//创建socket对象
socket = new WebSocket("ws://localhost:9001/websocket/"+ id);
//打开事件
socket.onopen = function (event) {
console.log("连接成功!!")
$("#content").append(id + "上线成功----------");
}
//获得消息时间
socket.onmessage = function (msg) {
console.log("获得消息++++++++"+msg.data)
$("#content").append(msg.data);
}
socket.onclose = function (p1) {
$("#content").append("下线");
}
//发生了错误事件
socket.onerror = function() {
alert("Socket发生了错误");
//此时可以尝试刷新页面
}
}
$(function () {
// 发送消息
$("#send").click(function () {
$.ajax({
type: "POST",
url: "/send/" + id + "/" + $("#text").val(),
dateType:text,
success: function (data) {
alert("发送成功")
},
error: function (data) {
alert("发送失败")
}
})
})
})
</script>