WebSocket服务端

该代码展示了如何使用Java的WebSocket API创建一个服务端,处理用户的连接、断开、消息收发。当用户连接时,增加在线计数并存储到客户端列表;关闭时减少计数并移除。消息处理包括向特定用户或所有用户广播。
摘要由CSDN通过智能技术生成

记录用到的WebSocket服务端。

import java.io.IOException;
import java.util.Map;
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;
@ServerEndpoint("/webSocket/{username}")  
    public class WebSocket { 
        private static int onlineCount = 0; 
        private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>(); 
        private Session session; 
        private String username; 
           
        @OnOpen 
        public void onOpen(@PathParam("username") String username, Session session) throws IOException { 
       
            this.username = username; 
            this.session = session; 
               
            addOnlineCount(); 
            clients.put(username, this);
            System.out.println(username+"已连接");
        } 
       
        @OnClose 
        public void onClose() throws IOException { 
            clients.remove(username); 
            try {
				this.session.close();
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
            subOnlineCount(); 
            System.out.println("关闭");
        } 
       
        @OnMessage 
        public void onMessage(String message) throws IOException { 
       
            JSONObject jsonTo = JSONObject.fromObject(message); 
            String mes = (String) jsonTo.get("message");
             
            if (!jsonTo.get("To").equals("All")){ 
                sendMessageTo(mes, jsonTo.get("To").toString()); 
            }else{ 
                sendMessageAll("给所有人"); 
            } 
        } 
       
        @OnError 
        public void onError(Session session, Throwable error) throws IOException { 
        	onClose();
        	System.out.println("发生错误");
            error.printStackTrace(); 
        } 
       
        public static void sendMessageTo(String message, String To) throws IOException { 
            // session.getBasicRemote().sendText(message); 
            //session.getAsyncRemote().sendText(message); 
            for (WebSocket item : clients.values()) { 
                if (item.username.equals(To) ) 
                    item.session.getAsyncRemote().sendText(message); 
            } 
        } 
           
        public void sendMessageAll(String message) throws IOException { 
            for (WebSocket item : clients.values()) { 
                item.session.getAsyncRemote().sendText(message); 
            } 
        } 
       
        public static synchronized int getOnlineCount() { 
            return onlineCount; 
        } 
       
        public static synchronized void addOnlineCount() { 
            WebSocket.onlineCount++; 
        } 
       
        public static synchronized void subOnlineCount() { 
            WebSocket.onlineCount--; 
        } 
       
        public static synchronized Map<String, WebSocket> getClients() { 
            return clients; 
        } 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值