实现WebSocket步骤:
第一步,创建一个类,此类主要是做WebSokect的服务器,还有监听方法
package com.dayuan.lifepartner.common.webSocket;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
@ServerEndpoint("/websocket/{userno}")
public class WebSocketTest {
private static int onlineCount = 0;
private static ConcurrentHashMap webSocketSet = new ConcurrentHashMap();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session WebSocketsession;
//当前发消息的人员编号
private String userno = "";
public void setUserno(String userno) {
this.userno = userno;
}
@OnOpen
public void onOpen(@PathParam(value = "userno") String param, Session WebSocketsession, EndpointConfig config) {
System.out.println(param);
userno = param;//接收到发送消息的人员编号
this.WebSocketsession = WebSocketsession;
webSocketSet.put(param, this);//加入map中
addOnlineCount(); //在线数加1
System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@SuppressWarnings("unused")
// @OnMessage
public void onMessage(String message, Session session) {
String [] sendMessage = message.split("[|]");
System.out.println("来自客户端的消息:" + message);
String [] user = message.split("[|]");
//群发消息
if (user.length== 1) {
sendAll(message);
} else {
//给指定的人发消息
sendToUser(message);
}
}
/**
* 给所有人发消息
* @param message
*/
public void sendAll(String message) {
System.out.println("给所人发信息");
String sendMessage = message.split("[|]")[0];
//遍历HashMap
for (String key : webSocketSet.keySet()) {
System.out.println("当前的key"+webSocketSet.keySet());
try {
//判断接收用户是否是当前发消息的用户
if (!userno.equals(key)) {
System.out.println("userno"+userno);
webSocketSet.get(key).sendMessage("用户" + userno + ": 广播" + " " + sendMessage);
System.out.println("key = " + key);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 给指定的人发送消息
* @param message
*/
@OnMessage
public void sendToUser(String message) {
System.out.println("给指定人发信息");
String sendUserno = message.split("[|]")[1];
String sendMessage = message.split("[|]")[0];
try {
System.out.println("webSocketSet.get(sendUserno)"+webSocketSet.get(sendUserno));
if (webSocketSet.get(sendUserno) != null) {
webSocketSet.get(sendUserno).sendMessage("用户" + userno + ": 广播" + " " + sendMessage);
} else {
System.out.println("当前用户不在线");
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
if (!userno.equals("")) {
webSocketSet.remove(userno); //从set中删除
subOnlineCount(); //在线数减1
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
}
/**
* 获取当前时间
*
* @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实例化WebSocket,调用.send方法。
Java后端WebSocket的Tomcat实现 Welcome 发送消息 发送人:WebSocket协议是基于TCP的一种新的网络协议,它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端,目前我实现的场景就是广播。 如需要源码可留言下方联系我。1234接收人: 关闭WebSocket连接 var websocket = null; var userno=document.getElementById('userno').innerHTML; //判断当前浏览器是否支持WebSocket if ('WebSocket' in window) { websocket = new WebSocket("ws://localhost:8080/WebSocket2/websocket/"+userno); } else { alert('当前浏览器 Not support websocket') } //发送消息 function send() { var message = document.getElementById('text').value;//要发送的消息内容 document.getElementById('message').innerHTML += ("发送人:"+userno+''+"---"+message) + ''; document.getElementById('message').style.color="red"; var ToSendUserno=document.getElementById('usernoto').value; //接收人编号:4567 message=message+"|"+ToSendUserno//将要发送的信息和内容拼起来,以便于服务端知道消息要发给谁 websocket.send(message); } //连接发生错误的回调方法 websocket.onerror = function () { setMessageInnerHTML("WebSocket连接发生错误"); }; //连接成功建立的回调方法 websocket.onopen = function () { setMessageInnerHTML("WebSocket连接成功"); } //接收到消息的回调方法 websocket.onmessage = function (event) { setMessageInnerHTML(event.data); } //连接关闭的回调方法 websocket.onclose = function () { setMessageInnerHTML("WebSocket连接关闭"); } //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function () { closeWebSocket(); } //将消息显示在网页上 function setMessageInnerHTML(sendMessage) { document.getElementById('message').innerHTML += sendMessage + ''; } //关闭WebSocket连接 function closeWebSocket() { websocket.close(); }
