群聊原型
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@Component
@ServerEndpoint(value = "/socket/{id}")
public class WebSocketServer {
private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);
private static int onLineCount = 0;
private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<String, WebSocketServer>();
private Session session;
private String id;
@OnOpen
public void onOpen(@PathParam("id")String id, Session session){
this.session = session;
this.id= id;
webSocketMap.put(id,this);
addOnLineCount();
LOGGER.info("有新的连接加入,id:{}!当前在线人数:{}",ip,getOnLineCount());
}
@OnClose
public void onClose(@PathParam("id")String id){
webSocketMap.remove(id);
subOnLineCount();
LOGGER.info("WebSocket关闭,id:{},当前在线人数:{}",id,getOnLineCount());
}
@OnMessage
public void onMessage(String message,Session session){
LOGGER.info("收到客户端的消息:{}",message);
}
@OnError
public void onError(Session session,Throwable error){
LOGGER.error("WebSocket发生错误");
error.printStackTrace();
}
public void sendMessage(String message){
try{
this.session.getBasicRemote().sendText(message);
}catch (IOException e){
e.printStackTrace();
LOGGER.info("发送数据错误:,id:{},message:{}",id,message);
}
}
public static void sendMessageAll(final String message){
Set<Map.Entry<String, WebSocketServer>> entries = webSocketMap.entrySet();
for (Map.Entry<String, WebSocketServer> entry : entries) {
final WebSocketServer webSocketServer = entry.getValue();
new Thread(new Runnable() {
@Override
public void run() {
webSocketServer.sendMessage(message);
}
}).start();
}
}
public static synchronized int getOnLineCount(){
return WebSocketServer.onLineCount;
}
public static synchronized void addOnLineCount(){
WebSocketServer.onLineCount++;
}
public static synchronized void subOnLineCount(){
WebSocketServer.onLineCount--;
}
public Session getSession(){
return session;
}
public void setSession(Session session){
this.session = session;
}
public static ConcurrentHashMap<String, WebSocketServer> getWebSocketMap() {
return webSocketMap;
}
public static void setWebSocketMap(ConcurrentHashMap<String, WebSocketServer> webSocketMap) {
WebSocketServer.webSocketMap = webSocketMap;
}
}
简单使用
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@Component
@ServerEndpoint(value = "/socket/{id}")
public class EndpointService {
private final static Logger LOGGER = LogManager.getLogger(EndpointService.class);
private HttpSession httpSession;
private Session session;
private static ConcurrentHashMap<String,EndpointService> webSocketMap = new ConcurrentHashMap<String, EndpointService>();
private String id;
@OnOpen
public void onOpen(@PathParam("id")String id, Session session){
this.session = session;
this.id= id;
webSocketMap.put(ip, this);
LOGGER.info("有新的连接加入,id:{}!当前在线人数:{}",id);
}
@OnClose
public void onClose(@PathParam("id")String ip){
webSocketMap.remove(id);
LOGGER.info("WebSocket关闭,id:{},当前在线人数:{}",id);
}
@OnMessage
public void onMessage(String message,Session session){
LOGGER.info("收到客户端的消息:{}",message);
sendMessageAll(message);
}
@OnError
public void onError(Session session,Throwable error){
LOGGER.error("WebSocket发生错误");
error.printStackTrace();
}
public static void sendMessageAll(final String message){
Set<Map.Entry<String, EndpointService>> entries = webSocketMap.entrySet();
for (Map.Entry<String, EndpointService> entry : entries) {
final EndpointService endpointService = entry.getValue();
new Thread(new Runnable() {
@Override
public void run() {
endpointService.sendMessage(message);
}
}).start();
}
}
public void sendMessage(String message){
try{
this.session.getBasicRemote().sendText(message);
}catch (IOException e){
e.printStackTrace();
LOGGER.info("发送数据错误:,id:{},message:{}",id,message);
}
}
}
前台代码
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" th:src="@{/js/jquery-2.1.1.min.js}"></script>
<style type="text/css">
.bis{
display: block;
}
</style>
</head>
<body>
<img src="/index/getCaptcha" style="width:80px; height: 30px;"/>
<div>
<label class="bis">
用户名:<input type="text" id="username" value="" />
</label>
<label class="bis">
编号:<input type="text" id="userid" value="" />
</label>
<label class="bis">
性别:<input type="text" id="gender" value="" />
</label>
<button onclick="joinIn()">加入</button><span id="errMag" style="color: red;"></span>
</div>
<div id="divWin" style="width: 400px;height: 200px;background-color: #bbe6ff;overflow-y: auto;">
</div>
<textarea id="editMsg" style="width: 400px;height: 100px;background-color: #bbffbc"></textarea>
<button onclick="sendMsg()">发送</button>
</body>
<script type="text/javascript">
let webSocket;
let userId;
let username;
$(function () {
})
function joinIn() {
let id = $("#userid").val();
let name = $("#username").val();
if (!id || !name) {
$("#errMag").text("加入失败,请输入用户信息!");
return false;
}else {
userId = id;
username = name;
connection();
}
}
function connection() {
let host = window.location.host;
let wsUri = `ws://${host}/socket/${userId}`;
webSocket = new WebSocket(wsUri);
$("#divWin").html($("#divWin").html()+wsUri);
webSocket.onopen = function () {
console.log(`<p>用户:${username}<span style='float: right;color: greenyellow;'>上线了</span></p>`);
$("#divWin").html($("#divWin").html()+`<p>用户:${username}<span style='float: right;color: greenyellow;'>上线了</span></p>`);
}
webSocket.onmessage = function (event) {
let result = JSON.parse(event.data);
console.log(result);
$("#divWin").html($("#divWin").html()+`<br/>${result.fromName}:${result.message}`);
}
webSocket.onclose = function () {
$("#divWin").html($("#divWin").html()+`用户:${username}<span style="color:red;">离线</span>`);
}
webSocket.onerror = function () {
console.log("=========οnerrοr=========");
$("#divWin").html($("#divWin").html()+"连接出错");
}
}
function sendMsg() {
let msg = $("#editMsg").val();
if (msg) {
let jsonMessage = {
"fromName": username,
"fromId": userId,
"toName": "",
"toId": "",
"message": msg
};
webSocket.send(JSON.stringify(jsonMessage));
$("#editMsg").val('');
}
}
</script>
</html>