1.建立项目
依赖已经自动配置好了,就不用添加了。
2、后端
建立这两个类,代码如下:
package com.example.websockettest;
//WebSocketConfig
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
//首先要注入ServerEndpointExporter,这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint。
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
package com.example.websockettest;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
/**
* @ServerEndpoint 注解是一个类层次的注解,它的功 能主要是将目前的类定义成一个websocket服务器端,
* 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
*/
@ServerEndpoint("/websocket")
@Component
public class WebSocketTest {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//用来存放每个客户端对应的MyWebSocket对象。
//使用Map来存放,其中Key可以为用户标识
private static HashMap<String,WebSocketTest> webSocketMap =new HashMap<>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
/**
* 连接建立成功调用的方法
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(Session session) throws IOException {
this.session = session;
webSocketMap.put(session.hashCode()+"",this); //加入map中
System.out.println("这个客户端的用户名:" + session.hashCode());
this.sendMessage("你分配的用户名:" + session.hashCode());
addOnlineCount(); //在线数加1
System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(){
webSocketMap.remove(this);//从map中删除
subOnlineCount(); //在线数减1
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) throws IOException {
//发送的用户号就是session.hashcode(),可以再加个map继续映射
//通过#*#*这个字符串来分割消息的组成,我随意设定的
int pos=message.indexOf("#*#*");
String realmessage=message.substring(0,pos);
//这个4是因为#*#*这个字符串长度为4
String realuser=message.substring(pos+4,message.length());
System.out.println("来自客户端的消息:" + realmessage);
//
WebSocketTest item=webSocketMap.get(realuser);
item.sendMessage(realmessage);
}
/**
* 发生错误时调用
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error){
System.out.println("发生错误");
error.printStackTrace();
}
/**
* 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
* @param message
* @throws IOException
*/
//给客户端传递消息
public void sendMessage(String message) throws IOException{
this.session.getBasicRemote().sendText(message);
//this.session.getAsyncRemote().sendText(message);
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketTest.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketTest.onlineCount--;
}
}
3.前端
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>My WebSocket</title>
</head>
<body>
WebSocket<br/>
<input id="text" type="text" placeholder="消息"/>
<input id="user" type="text" placeholder="用户名"/>
<button onclick="send()">发送消息</button>
<button onclick="closeWebSocket()">关闭</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
var websocket = null;
//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
websocket = new WebSocket("ws://localhost:8080/websocket");
}
else{
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function(){
setMessageInnerHTML("连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function(event){
setMessageInnerHTML("连接建立成功");
}
//接收到消息的回调方法
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function(){
setMessageInnerHTML("连接关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function(){
websocket.close();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//关闭连接
function closeWebSocket(){
websocket.close();
}
//发送消息
function send(){
var message = document.getElementById('text').value;
var user = document.getElementById('user').value;
websocket.send(message+"#*#*"+user);
}
</script>
</html>
4.效果演示
理论上可以开多个客户端,各自点对点通信。
感觉有点类似邮件
本篇博客的大部分内容转载自:https://www.cnblogs.com/xdp-gacl/p/5193279.html
他实现的是消息群发的功能,我再次基础上,改动了下变成这样的,服务器当作消息的中转站,如果有更好的想法,欢迎交流。