使用本方法不需要任何jar包
var ws = new WebSocket(url,[protocol]);//url:指定连接的服务器,protocol:可接受的子协议。
var ws = new WebSocket("ws://"+location.host+"/websocket/"+用户ID);//location.host是客户端的ip。这是握手协议,登陆时不要直接localhost:8080这样登陆,而是192.168.0.135:8080或www.edu.com这样登陆。
执行上面语句之后,客户端就会与服务器进行连接。
//先握手,并查看客户端的浏览器是否支持websocket协议
var ws = "";
if ('WebSocket' in window) {
ws=new WebSocket("ws://"+location.host+"/websocket/"+userInfo.userId);
} else if ('MozWebSocket' in window) {
ws= new MozWebSocket("ws://"+location.host+"/websocket/"+userInfo.userId);
} else {
layui.use(['layer'], function(){
var layer = layui.layer;
layer.alert("您的浏览器不支持webscoket协议,建议使用新版谷歌、火狐等浏览器,请勿使用IE10以下浏览器,360浏览器请使用极速模式,不要使用兼容模式!");
});
}
//连接发生错误的回调方法
ws.onerror = function () {
alert("WebSocket连接发生错误");
};
//连接成功建立的回调方法
ws.onopen = function () {
alert("WebSocket连接成功");
}
//接收到消息的回调方法,websocket的controller里的onMessage方法session_to传过来的值
ws.onmessage = function (event) {
alert(event.data);
}
//连接关闭的回调方法
ws.onclose = function () {
alert("WebSocket连接关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
}
//关闭WebSocket连接
function closeWebSocket() {
ws.close();
}
//发送消息
function send() {
ws.send(JSON.stringify({
id: id,content: content
}));这里是传过去个json格式的值,和map差不多,前面是key,后面是值
}
package com.jykj.websocket;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import net.sf.json.JSONObject;
/**
* @ServerEndpoint 注解:websocket是ws时的地址,后面是用户ID
*/
@ServerEndpoint("/websocket/{userInfo}")
public class websocket {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
private static ConcurrentHashMap<Integer,Session> mapUS = new ConcurrentHashMap<Integer,Session>();//根据用户找session
private static ConcurrentHashMap<Session,Integer> mapSU = new ConcurrentHashMap<Session,Integer>();//根据session找用户
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
/**
* 连接建立成功调用的方法
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(Session session,@PathParam("userInfo") Integer userInfo){
this.session = session;
mapUS.put(userInfo,session);//添加唯一标识的用户ID为key,session为值
mapSU.put(session,userInfo);//添加session为key,唯一标识的用户ID为值
addOnlineCount(); //在线数加1
System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(Session session){
Integer userId = mapSU.get(session);
mapUS.remove(userId);
mapSU.remove(session);
subOnlineCount(); //在线数减1
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
JSONObject jsonObject=JSONObject.fromObject(message);
Integer id = jsonObject.getInt("id");//获取ID信息,群发就不用了
String content = jsonObject.getString("content");//获取发送信息,群发还是需要的
Session session_to=mapUS.get(id);//这是发送个人信息
//群发消息
/*for(websocket item: webSocketSet){
try {
item.sendMessage(content);//这里是调用了下面的sendMessage方法
} catch (IOException e) {
e.printStackTrace();
continue;
}
}*/
if(id==null||content==null||content==""){return ;}
session_to.getAsyncRemote().sendText(content);//群发就不用了,个人的session发送过去
}
/**
* 发生错误时调用
* @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.getAsyncRemote().sendText(message);//发送给全局变量session中用户信息
}*/
public static synchronized int getOnlineCount() {
return onlineCount;//返回在线人数
}
public static synchronized void addOnlineCount() {
websocket.onlineCount++;//在线人数+1
}
public static synchronized void subOnlineCount() {
websocket.onlineCount--;//在线人数-1
}
}
WebSocket属性
属性 | 描述 |
ws.readyState | readyState表示连接状态:0-未连接、1-已连接,可进行通信、2-连接正在进行关闭、3-连接已关闭或连接不上 |
ws.bufferedAmount | bufferedAmount已被send()放在队列等待传输,但还没有发出UTF-8文本字节数 |
WebSocket事件
事件 | 事件处理程序 | 描述 |
open | ws.onopen | 连接建立时触发 |
message | ws.onmessage | 客户端接收服务端数据时触发 |
error | ws.onerror | 通信发生错误时触发 |
close | ws.onclose | 连接关闭时触发 |
WebSocket方法
方法 | 描述 |
ws.send() | 使用连接发送数据 |
ws.close() | 关闭连接 |
我是看静默虚空的理论:点击打开链接