java代码
package com.webSocket;
import net.sf.json.JSONObject;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.*;https://img-ask.csdn.net/upload/201910/09/1570620105_17011.png
/**
* @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
* 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
*/
@ServerEndpoint(value = "/webSocketOneToOne/{param}")
public class WebSocketOneToOne {
// 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount;
//实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key为用户标识
private static Map<String,WebSocketOneToOne> connections = new ConcurrentHashMap<>();
// 与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
private String role;
private String socketId;
/**
* 连接建立成功调用的方法
*
* @param session
* 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(@PathParam("param") String param, Session session) {
this.session = session;
String[] arr = param.split(",");
this.role = arr[0]; //用户标识
this.socketId = arr[1]; //会话标识
connections.put(role,this); //添加到map中
addOnlineCount(); // 在线数加
System.out.println("有新连接加入!新用户:"+role+",当前在线人数为" + getOnlineCount());
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
connections.remove(role); // 从map中移除
subOnlineCount(); // 在线数减
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message
* 客户端发送过来的消息
* @param session
* 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
JSONObject json=JSONObject.fromObject(message);
String string = null; //需要发送的信息
String to = null; //发送对象的用户标识
if(json.has("message")){
string = (String) json.get("message");
}
if(json.has("role")){
to = (String) json.get("role");
}
send(string,role,to,socketId);
}
/**
* 发生错误时调用
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
//发送给指定角色
public static void send(String msg,String from,String to,String socketId){
try {
//to指定用户
WebSocketOneToOne con = connections.get(to);
if(con!=null){
if(socketId==con.socketId||con.socketId.equals(socketId)){
con.session.getBasicRemote().sendText(from+"说:"+msg);
}
}
//from具体用户
WebSocketOneToOne confrom = connections.get(from);
if(confrom!=null){
if(socketId==confrom.socketId||confrom.socketId.equals(socketId)){
confrom.session.getBasicRemote().sendText(from+"说:"+msg);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketOneToOne.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketOneToOne.onlineCount--;
}
}
# jsp代码
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/10/9 0009
Time: 下午 4:19
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<script>
var websocket = null;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
var url = "ws://localhost:8080/webSocket/webSocketOneToOne/1,123"
websocket = new WebSocket(url);
} else {
alert('当前浏览器 Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function() {
setMessageInnerHTML("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function() {
setMessageInnerHTML("WebSocket连接成功");
}
//接收到消息的回调方法
websocket.onmessage = function(event) {
console.log("回调信息",event.data)
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function() {
setMessageInnerHTML("WebSocket连接关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function() {
closeWebSocket();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
//发送消息
function send() {
var message = document.getElementById('text').value;
//message作为发送的信息,role作为发送的对象标识,socketId是此次会话的标识
websocket.send(JSON.stringify({'message': message, 'role': '2', 'socketId': "123"}));
}
</script>
<input id="text" type="text" />
<button οnclick="send()">发送消息</button>
<button οnclick="closeWebSocket()">关闭WebSocket连接</button>
<div id="message"></div>
</body>
</html>
# pom依赖
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>https://img-ask.csdn.net/upload/201910/09/1570620105_17011.png
<artifactId>json-lib-ext-spring</artifactId>
<version>1.0.2</version>https://img-ask.csdn.net/upload/201910/09/1570620105_17011.png
</dependency>
</dependencies>

# 运行之后出现的情况
显示连接失败