zoukankan      html  css  js  c++  java
  • WebSocket教程(二)

    运行环境:jdk8 tomcat8   无须其他jar包。
    
    package com.reach.socketController;
    
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.concurrent.CopyOnWriteArraySet;
    
    import javax.annotation.Resource;
    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(value ="/newwebsocket/{userId}")
    public class Webcomment {
        @Resource
        private Webcomment webcomment;
        
        //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
        private static int onlineCount = 0;
        //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
        private static CopyOnWriteArraySet<Webcomment> webSocketSet = new CopyOnWriteArraySet<Webcomment>();  
      //线程安全的Map  
        private static ConcurrentHashMap<String,Session> webSocketMap = new ConcurrentHashMap<String,Session>();//建立连接的方法
        @OnOpen
        public void onOpen(Session session,@PathParam("userId")String  userId){
            /*获取从/websocket开始的整条链接,用于获取userId?***=***的参数
            String uri = session.getRequestURI().toString();*/
        webSocketMap.put(userId, session);
        addOnlineCount(); //在线数加
        System.out.println(userId+"进入聊天室");
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
        }
        
        /**
        * 连接关闭调用的方法
        */
        @OnClose
        public void onClose(Session session){
        Map<String, String> map = session.getPathParameters();
        webSocketMap.remove(map.get("userId")); //从set中删除
        for(String user:webSocketMap.keySet()){
        System.out.println(user);
        }
        subOnlineCount(); //在线数减
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
        }
        
        /**
        * 收到客户端消息后调用的方法
        * @param message 客户端发送过来的消息
        * @param session 可选的参数
        */
        @OnMessage
        public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
        //获取用户ID
        Map<String, String> map = session.getPathParameters();
        String userId = map.get("userId");
        for(String user:webSocketMap.keySet()){
            try {
                sendMessage(user+"你好,我是"+userId+"   "+message,webSocketMap.get(user));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        }
        
        /**
        * 发生错误时调用
        * @param session
        * @param error
        */
        @OnError
        public void onError(Session session, Throwable error){
        System.out.println("发生错误");
        error.printStackTrace();
        }
        
        public void sendMessage(String message,Session session) throws IOException{
            if(session.isOpen()){
            session.getAsyncRemote().sendText(message);
            }
            //this.session.getAsyncRemote().sendText(message);
            }
        
        
        
        public static synchronized int getOnlineCount() {
            return onlineCount;
            }
        public static synchronized void addOnlineCount() {
            Webcomment.onlineCount++;
            }
        public static synchronized void subOnlineCount() {
            Webcomment.onlineCount--;
            }
    }

    html代码,可以单独建立html,无须放在项目中

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
     <head>
      <title> new document </title>
      <meta name="generator" content="editplus" />
      <meta name="author" content="" />
      <meta name="keywords" content="" />
      <meta name="description" content="" />
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <script src="jquery-1.8.3.min.js" type="text/javascript"></script>
     </head>
    
     <body>
    
    
      <center>
    Welcome<br/><input id="text" type="text"/>
    <button onclick="send()">发送消息</button>
    <hr/>
    <button onclick="closeWebSocket()">关闭WebSocket连接</button>
    <hr/>
    <div id="message"></div>
    
    
    
    
     </body>
     <script type="text/javascript">
    var websocket = null;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
    alert('当前浏览器支持 websocket');
    websocket = new WebSocket("ws://localhost:8080/Y-websocket/newwebsocket/234");
    }
    else {
    alert('当前浏览器 Not support websocket')
    }
    //连接发生错误的回调方法
    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(innerHTML) {
    document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }
    //关闭WebSocket连接
    function closeWebSocket() {
    websocket.close();
    }
    //发送消息
    function send() {
    var message = document.getElementById('text').value;
    websocket.send(message);
    }
    </script>
    </html>

    友情提示: 向客户端发送信息  sendText()是用来传输字符串的,有一个sendObject()方法可以通过转码器发送javabean。  

           但是这里我们不推荐,因为非常麻烦。最简单的办法,就是把要发送的bean转成json字符串。 bean转json

           然后在页面将接收的json字符串转成json:JSON.parse(event.data)

  • 相关阅读:
    输入流输出流
    WIN32_FIND_DATA
    typeid
    为什么要内存对齐 Data alignment: Straighten up and fly right
    fatal error C1010: 在查找预编译头时遇到意外的文件结尾。是否忘记了向源中添加“#include "stdafx.h
    memcmp
    DPI
    英寸、 Picas、 点、 跨度和 Twips 之间的关系
    如何解决 “fatal error C1083: ”无法打开包括文件
    hdoj 1269迷宫城堡解题报告
  • 原文地址:https://www.cnblogs.com/longqingyang/p/7929548.html
Copyright © 2011-2022 走看看