环境:tomcat7.0.55 jdk1.7
MyServer.java
package web;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import net.sf.json.JSONObject;
//该注解用来指定一个URI,客户端可以通过这个URI来连接到WebSocket。类似Servlet的注解mapping。无需在web.xml中配置。
@ServerEndpoint("/coke/{id}/{dh}")
public class MyServer {
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyServer对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
private static ConcurrentHashMap<String, MyServer> webSocketMap = new ConcurrentHashMap<String, MyServer>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
private String userno="";
/**
* 连接建立成功调用的方法
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(@PathParam("id") String oid,@PathParam("dh") String ddh, Session session){
userno = id+"_"+dh;
this.session = session;
webSocketMap.put(id+"_"+dh,this);//加入到Map
addOnlineCount(); //在线数加1
System.out.println("新用户【"+id+"_"+dh+"】加入!当前在线人数为" + getOnlineCount());
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(@PathParam("id") String oid,@PathParam("dh") String ddh){
webSocketMap.remove(id+"_"+dh); //从set中删除
subOnlineCount(); //在线数减1
System.out.println("用户【"+id+"_"+dh+"】退出!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) {
JSONObject obj = JSONObject.fromObject(message);
String touser = obj.get("userid").toString();
//群发消息
if (userno.equals(touser)) {
sendAll(message);
} else {
//给指定的人发消息
sendToUser(message);
}
}
/**
* 给指定的人发送消息
* @param message
*/
private void sendToUser(String message) {
System.out.println("来自客户端的消息:" + message);
JSONObject obj = JSONObject.fromObject(message);
//向JSON对象中添加发送时间
obj.put("date", getNowTime());
String userid = obj.get("userid").toString();
//给指定的人发送消息
System.out.println("推送给客户端的消息:" + obj.toString());
// String now = getNowTime();
try {
if (webSocketMap.get(userid) != null) {
//webSocketMap.get(sendUserno).sendMessage(now + "用户" + userno + "发来消息:" + " <br/> " + sendMessage);
webSocketMap.get(userid).sendMessage(obj.toString());
webSocketMap.get(userno).sendMessage(obj.toString());
} else {
System.out.println("当前用户不在线");
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 给所有人发消息
* @param message
*/
private void sendAll(String message) {
System.out.println("来自客户端的消息:" + message);
JSONObject obj = JSONObject.fromObject(message);
//向JSON对象中添加发送时间
obj.put("date", getNowTime());
//群发消息
System.out.println("推送给客户端的消息:" + obj.toString());
//遍历HashMap
for (String key : webSocketMap.keySet()) {
try {
//判断接收用户是否是当前发消息的用户
//webSocketMap.get(key).sendMessage(now + "用户" + userno + "发来消息:" + " <br/> " + sendMessage);
webSocketMap.get(key).sendMessage(obj.toString());
System.out.println("key = " + key);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 发生错误时调用
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error){
System.out.println("发生错误:"+error.getMessage());
error.printStackTrace();
}
/**
* 获取当前时间
*
* @return
*/
private String getNowTime() {
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = format.format(date);
return time;
}
/**
* 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException{
//同步发送 由于同步特性,第二行的消息必须等待第一行的发送完成才能进行,而第一行的剩余部分消息要等第二行发送完才能继续发送,所以在第二行会抛出IllegalStateException异常。
//如果要使用getBasicRemote()同步发送消息,则避免尽量一次发送全部消息,使用部分消息来发送。
// this.session.getBasicRemote().sendText(message);
//异步发送
this.session.getAsyncRemote().sendText(message);
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
MyServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
MyServer.onlineCount--;
}
}
jsp文件
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String pathserver = request.getServerName();
if(pathserver.equalsIgnoreCase("localhost")){
pathserver = request.getServerName()+":"+request.getServerPort();
}
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My WebSocket</title>
</head>
<input id="serverpath" type="hidden" value="<%=pathserver%>" />
<body>
Welcome<br/>
<input type="text" id="mb" value="" style="display: inherit;">
<div id="message" style="width: 95%; height: 300px; overflow-y: auto; overflow-x: hidden;word-wrap: break-word;padding: 10px 15px;border: 1px solid darkcyan;margin: 14px 0px;">
</div>
<input id="text" type="text" /><button onclick="send()">发送</button> <button onclick="closeWebSocket()">关闭</button>
<script type="text/javascript" src="js/websocket.my.js"></script>
<script type="text/javascript">
var oid = '${param.oid}';
var ddh = '${param.ddh}';
var websocket = null;
var serverpath = document.getElementById('serverpath').value;
//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
websocket = new WebSocket("ws://"+serverpath+"/MyWebsockettest/coke/"+id+"/"+dh);
}else if('MozWebSocket' in window){
websocket = window.MozWebSocket("ws://"+serverpath+"/MyWebsockettest/coke/"+id+"/"+dh);
}
//连接发生错误的回调方法
websocket.onerror = function(event){
document.getElementById('message').innerHTML += event+'<br/><br/>';
//setMessageInnerHTML("error:"+event);
};
//连接成功建立的回调方法
websocket.onopen = function(){
document.getElementById('message').innerHTML += '成功建立连接!<br/><br/>';
//setMessageInnerHTML("成功建立连接!");
};
//接收到消息的回调方法
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
};
//连接关闭的回调方法
websocket.onclose = function(){
document.getElementById('message').innerHTML += '成功关闭连接!<br/><br/>';
//setMessageInnerHTML("成功关闭连接!");
};
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function(){
websocket.close();
};
var nickname = "游客"+Math.floor(Math.random() * Math.floor(9999999))+new Date().getTime();
//将消息显示在网页上
function setMessageInnerHTML(innerHTML){
var gettext = eval('('+innerHTML+')');
var context = gettext.context;
var nicknameh = gettext.nickname;
var date = gettext.date;
var sty = "";
var sty2 = "";
if(nickname==nicknameh){
sty ="text-align: right;";
sty2="margin-left: 50%;";
}
document.getElementById('message').innerHTML += "<div style=\"padding: 10px 1px;"+sty+"\"><div style=\"font-size: 12px;color: darkgray;\">"+nicknameh+"</div><div style=\"font-size: 10px;color: darkgray;\">"+date+"</div><div style=\"width: 50%;"+sty2+"\">"+ context + "</div></div>";
}
//关闭连接
function closeWebSocket(){
websocket.close();
}
//发送消息
function send(){
var touser = document.getElementById('mb').value||"0";
var message = document.getElementById('text').value;
if(touser=="0"||touser==""){
touser = id+"_"+dh;
}
if(message.length>=1){
var obj = JSON.stringify({
userid:touser,
nickname:nickname,
context:message
});
websocket.send(obj.toString());
document.getElementById('text').value='';
}else{
alert("还没有输入信息哦~_~");
}
}
</script>
</body>
</html>
web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>coke</servlet-name>
<servlet-class>web.MyServer</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>coke</servlet-name>
<url-pattern>/MyWebsockettest/coke</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
tomcat 的 context.xml 中的<Context>节点内添加
<Context>
<Loader delegate="true"/>
</Context>