Java WebSocket服务器

/ java / 没有评论 / 413浏览

Java WebSocket服务器


package com.atree.flyone.websocket;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

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;

@ServerEndpoint("/webSocket/{userId}")
public class WebSocket {

	// 与某个客户端的连接会话,需要通过它来给客户端发送数据
	private Session session;
	private static Map<String, Session> sessionPool = new HashMap<String, Session>();
	private static Map<String, String> sessionIds = new HashMap<String, String>();

	/**
	 * 用户连接时触发
	 * @param session
	 * @param userid
	 * @throws Exception 
	 * @throws NumberFormatException 
	 */
	@OnOpen
	public void onOpen(Session session, @PathParam(value = "userId") String userId) {
		this.session = session;
		sessionPool.put(userId, session);
		sessionIds.put(session.getId(), userId);
		System.out.println("有新连接加入!id为:" + userId + ",当前在线人数为" + sessionPool.size());
	}

	/**
	 * 收到信息时触发
	 * @param message
	 */
	@OnMessage
	public void onMessage(String message) {
		System.out.println("当前发送人sessionid为" + session.getId() + "发送内容为" + message);
	}

	/**
	 * 连接关闭触发
	 */
	@OnClose
	public void onClose() {
		sessionPool.remove(sessionIds.get(session.getId()));
		sessionIds.remove(session.getId());
	}

	/**
	 * 发生错误时触发
	 * @param session
	 * @param error
	 */
	@OnError
	public void onError(Session session, Throwable error) {
		error.printStackTrace();
	}

	/**
	 * 信息发送的方法
	 * @param message
	 * @param userId
	 */
	public static void sendMessage(String message, String userId) {
		Session s = sessionPool.get(userId);
		if (s != null) {
			try {
				System.out.println("当前发送对象Id为" + userId + ",发送内容为" + message);
				s.getBasicRemote().sendText(message);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 获取当前连接数
	 * @return
	 */
	public static int getOnlineNum() {
		return sessionPool.size();
	}

	/**
	 * 获取在线用户名以逗号隔开
	 * @return
	 */
	public static String getOnlineUsers() {
		StringBuffer users = new StringBuffer();
		for (String key : sessionIds.keySet()) {
			users.append(sessionIds.get(key) + ",");
		}
		return users.toString();
	}

	/**
	 * 信息群发
	 * @param msg
	 */
	public static void sendAll(String msg) {
		for (String key : sessionIds.keySet()) {
			sendMessage(msg, sessionIds.get(key));
		}
	}

	/**
	 * 多个人发送给指定的几个用户
	 * @param msg
	 * @param persons 用户s
	 */

	public static void SendMany(String msg, String[] persons) {
		for (String userid : persons) {
			sendMessage(msg, userid);
		}
	}

}