webSocket

1.导入jar包

<dependency>
   <groupId>javax.websocket</groupId>
   <artifactId>javax.websocket-api</artifactId>
   <version>1.0</version>
</dependency>

3.外部引入js

var websocket = null;

//判断当前浏览器是否支持WebSocket
if('WebSocket' in window){
    websocket = new WebSocket("ws://lb.t.zijinshe.com/cms/websocket/"+user);
}
else{
alert('Not support websocket')
}

//连接发生错误的回调方法
websocket.onerror = function(){
setMessageInnerHTML("error");
};

//连接成功建立的回调方法
websocket.onopen = function(){
setMessageInnerHTML("open");
// websocket.send("ff");
}

//接收到消息的回调方法
websocket.onmessage = function(event){
// $("#msg").val(event.data);
tip(event.data);
setMessageInnerHTML(event.data);
}

//连接关闭的回调方法
websocket.onclose = function(){
setMessageInnerHTML("close");
}

//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function(){
    websocket.close();
}

//将消息显示在网页上
function setMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}

//关闭连接
function closeWebSocket(){
    websocket.close();
}
//发送消息
function send(){
var message = document.getElementById('text').value;
websocket.send(message);
}

4.java核心处理类

@ServerEndpoint("/websocket/{user}")
public class WebSocket {

private static int onlineCount = 0;


    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<WebSocket>();

    private static Map<String, WebSocket> webSocketSets = new HashMap<String, WebSocket>();


    private Session session;

@OnMessage
public void onMessage(String message,Session session)
throws IOException, InterruptedException {

// Print the client message for testing purposes
System.out.println("Received: " + message);

// Send the first message to the client
session.getBasicRemote().sendText("This is the first server message");

// Send 3 messages to the client every 5 seconds
//        int sentMessages = 0;
//        while(sentMessages < 3){
//            Thread.sleep(5000);
//            session.getBasicRemote().
//                    sendText("This is an intermediate server message. Count: "
//                            + sentMessages);
//            sentMessages++;
//        }

//        for(WebSocket item: webSocketSet){
//            System.out.println(item);
//            item.sendMessage(message);
//        }

System.out.println("size: " + webSocketSets.size());

//        for(String item:webSocketSets.keySet()){
//            if(item.equals(user)){
//                System.out.println(item+"--------------------"+webSocketSets.get(item));
//                webSocketSets.get(item).sendMessage(message);
//            }
//        }

        // Send a final message to the client
session.getBasicRemote().sendText(message);
}

@OnOpen
public void onOpen (@PathParam("user") String user, Session session) {
this.session = session;
webSocketSet.add(this);     //加入set中
addOnlineCount();           //在线数加1

webSocketSets.put(user,this);

System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
System.out.println("Client connected");
}

@OnClose
public void onClose () {
webSocketSet.remove(this);  //从set中删除
subOnlineCount();           //在线数减1
System.out.println("Connection closed");
}


public void sendMessage(String message) throws IOException{
this.session.getBasicRemote().sendText(message);
}

public static synchronized int getOnlineCount() {
return onlineCount;
}

public static synchronized void addOnlineCount() {
         WebSocket.onlineCount++;
}

public static synchronized void subOnlineCount() {
        WebSocket.onlineCount--;
}

/**
     * 发送消息
     * @param userName
* @param message
* @throws IOException
     */
public void sendMessageToUser(String userName, String message) throws IOException {

        System.out.println("size: " + webSocketSets.size());

        for(String item:webSocketSets.keySet()){
if(item.equals(userName)){
                System.out.println(item+"--------------------"+webSocketSets.get(item));
webSocketSets.get(item).sendMessage(message);
}
        }
    }

/**
     * 发送消息给给所有人
     * @param message
* @throws IOException
     */
public void sendMessageToUsers(String message) throws IOException {

        System.out.println("size: " + webSocketSets.size());

        for(String item:webSocketSets.keySet()){
webSocketSets.get(item).sendMessage(message);
}
    }
}

4.编写jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML>
<html>
<head>
    <base href="<%=basePath%>">
    <title>My WebSocket</title>
    <script type="text/javascript">
var user = "${user}";
</script>
</head>

<body>
Welcome<br/>
<input id="text" type="text" /><button οnclick="send('TTT')">Send</button>    <button οnclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>



<script src="${basePath}/cms/static/socket.js"></script>


</html>

转载于:https://my.oschina.net/u/2546238/blog/968138

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值