这两天因为有需要学习了一下WebSocket。在看了大量博客之后,发现网上实现WebSocket基本都是用tomcat,网上对于所要引用包也是众说纷纭。参考别人代码后搬过来自己的jetty环境下发现各种报错,前台请求都是404,焦头烂额。后来发现一位老哥写的文章,jetty跑websocket踩的坑。原文传送门:https://blog.csdn.net/qq_21413417/article/details/73863913。
总结了一下主要是两个问题:1.jetty版本至少需要9.0+(我用的是9.4)。
2.使用eclipse跑jetty需要勾选websocket support。
没错。。就是这么两个问题困扰了好久。。
代码实现主要参考这位老哥:https://blog.csdn.net/qq545923664/article/details/53517972
下面上代码。
后端实现:
package com.yyy.school.share.util;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.socket.server.standard.SpringConfigurator;
import com.yyy.school.share.dao.ShareDao;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
/**
* @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
* 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
* @ServerEndpoint 可以把当前类变成websocket服务类
*/
@Component
@ServerEndpoint("/websocket/{nowUid}")
public class WebSocketTest {
@Autowired
private ShareDao shareDao;
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
private static ConcurrentHashMap<String, WebSocketTest> webSocketSet = new ConcurrentHashMap<String, WebSocketTest>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session WebSocketsession;
//当前发消息的人员编号
private String nowUid = "";
public static WebSocketTest webSocketTest;
@PostConstruct
public void init() {
webSocketTest = this;
}
/**
* 连接建立成功调用的方法
*
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(@PathParam(value = "nowUid") String param, Session WebSocketsession, EndpointConfig config) {
System.out.println(param);
nowUid = param;//接收到发送消息的人员编号
this.WebSocketsession = WebSocketsession;
webSocketSet.put(param, this);//加入map中
addOnlineCount(); //在线数加1
System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
if (!nowUid.equals("")) {
webSocketSet.remove(nowUid); //从set中删除
subOnlineCount(); //在线数减1
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@SuppressWarnings("unused")
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
sendToUser(message);
// //群发消息
// if (1 < 2) {
// sendAll(message);
// } else {
// //给指定的人发消息
// sendToUser(message);
// }
}
/**
* 给指定的人发送消息
* @param message
*/
public void sendToUser(String messageStr) {
String toUid = messageStr.split("[|]")[1];
String message = messageStr.split("[|]")[0];
String now = getNowTime();
try {
if (webSocketSet.get(toUid) != null) {
webSocketSet.get(toUid).sendMessage(now + "用户" + nowUid + "发来消息:" + " <br/> " + message);
webSocketTest.shareDao.addToChatLog(nowUid, toUid, message, 1);
} else {
System.out.println(toUid + "当前用户不在线");
webSocketTest.shareDao.addToChatLog(nowUid, toUid, message, 0);
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 给所有人发消息
* @param message
*/
private void sendAll(String message) {
String now = getNowTime();
String sendMessage = message.split("[|]")[0];
//遍历HashMap
for (String key : webSocketSet.keySet()) {
try {
//判断接收用户是否是当前发消息的用户
if (!nowUid.equals(key)) {
webSocketSet.get(key).sendMessage(now + "用户" + nowUid + "发来消息:" + " <br/> " + sendMessage);
System.out.println("key = " + key);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 获取当前时间
*
* @return
*/
private String getNowTime() {
Date date = new Date();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = format.format(date);
return time;
}
/**
* 发生错误时调用
*
* @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.WebSocketsession.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--;
}
}
前端代码(JSP文件):
<!DOCTYPE html>
<html>
<head>
<title>WebSocket/SockJS Echo Sample (Adapted from Tomcat's echo sample)</title>
<style type="text/css">
#connect-container {
float: left;
width: 400px
}
#connect-container div {
padding: 5px;
}
#console-container {
float: left;
margin-left: 15px;
width: 400px;
}
#console {
border: 1px solid #CCCCCC;
border-right-color: #999999;
border-bottom-color: #999999;
height: 170px;
overflow-y: scroll;
padding: 5px;
width: 100%;
}
#console p {
padding: 0;
margin: 0;
}
</style>
<script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>
<script type="text/javascript">
var ws = null;
var url = null;
var transports = [];
function setConnected(connected) {
document.getElementById('connect').disabled = connected;
document.getElementById('disconnect').disabled = !connected;
document.getElementById('echo').disabled = !connected;
}
function connect() {
alert("url:"+url);
if (!url) {
alert('Select whether to use W3C WebSocket or SockJS');
return;
}
ws = (url.indexOf('sockjs') != -1) ?
new SockJS(url, undefined, {protocols_whitelist: transports}) : new WebSocket(url);
ws.onopen = function () {
setConnected(true);
log('Info: connection opened.');
};
ws.onmessage = function (event) {
log('Received: ' + event.data);
};
ws.onclose = function (event) {
setConnected(false);
log('Info: connection closed.');
log(event);
};
}
function disconnect() {
if (ws != null) {
ws.close();
ws = null;
}
setConnected(false);
}
function echo() {
if (ws != null) {
var message = document.getElementById('message').value;
log('Sent: ' + message);
ws.send(message);
} else {
alert('connection not established, please connect.');
}
}
function updateUrl(urlPath) {
if (urlPath.indexOf('sockjs') != -1) {
url = urlPath;
document.getElementById('sockJsTransportSelect').style.visibility = 'visible';
}
else {
if (window.location.protocol == 'http:') {
url = 'ws://' + window.location.host + urlPath;
} else {
url = 'wss://' + window.location.host + urlPath;
}
document.getElementById('sockJsTransportSelect').style.visibility = 'hidden';
}
}
function updateTransport(transport) {
alert(transport);
transports = (transport == 'all') ? [] : [transport];
}
function log(message) {
var console = document.getElementById('console');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.appendChild(document.createTextNode(message));
console.appendChild(p);
while (console.childNodes.length > 25) {
console.removeChild(console.firstChild);
}
console.scrollTop = console.scrollHeight;
}
</script>
</head>
<body>
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets
rely on Javascript being enabled. Please enable
Javascript and reload this page!</h2></noscript>
<div>
<div id="connect-container">
<input id="radio1" type="radio" name="group1" οnclick="updateUrl('/school_share/websocket');">
<label for="radio1">W3C WebSocket</label>
<br>
<input id="radio2" type="radio" name="group1" οnclick="updateUrl('/school_share/marco/sockJS');">
<label for="radio2">SockJS</label>
<div id="sockJsTransportSelect" style="visibility:hidden;">
<span>SockJS transport:</span>
<select οnchange="updateTransport(this.value)">
<option value="all">all</option>
<option value="websocket">websocket</option>
<option value="xhr-polling">xhr-polling</option>
<option value="jsonp-polling">jsonp-polling</option>
<option value="xhr-streaming">xhr-streaming</option>
<option value="iframe-eventsource">iframe-eventsource</option>
<option value="iframe-htmlfile">iframe-htmlfile</option>
</select>
</div>
<div>
<button id="connect" οnclick="connect();">Connect</button>
<button id="disconnect" disabled="disabled" οnclick="disconnect();">Disconnect</button>
</div>
<div>
<textarea id="message" style="width: 350px">Here is a message!</textarea>
</div>
<div>
<button id="echo" οnclick="echo();" disabled="disabled">Echo message</button>
</div>
</div>
<div id="console-container">
<div id="console"></div>
</div>
</div>
</body>
</html>