• Websocket简单例子


    websocket是Html5的一个协议,也就是说距离我们2016年就几年时间,其他原理我就不说了,直接讲例子

    一、准备材料:1、一个开发工具必须支持javaEE7的,原因是javaEE6或以下不支持websocket,我是使用的开发工具是myeclipse2015,这里给各位百度云盘

      链接: https://pan.baidu.com/s/1eS3DrPK 密码: 4fe1,里面有破解的工具,很方便

                      2、tomcat8.0以上、JDK7.0以上(这个也许就是websocket是近几年的原因)

    二、创建一个web项目,必须选择JavaEE7.0以上(图1-1)

                                    图1-1

    三、

    (1)、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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title>My JSP 'index.jsp' starting page</title>
        <meta http-equiv="pragma" content="no-cache">
        <meta http-equiv="cache-control" content="no-cache">
        <meta http-equiv="expires" content="0">    
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
        <meta http-equiv="description" content="This is my page">
        <meta content="text/html";charset="utf-8">
        <script src="<%=request.getContextPath()%>/js/jquery-2.1.4.min.js" ></script>
        <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
        -->
      </head>
      
      <body>
        <form>
             <h1>WebSocket送信实例</h1>
             <input type="text" id="message"  disabled="disabled" required>
             <input type="button" onclick="echo()" disabled="disabled" value="提交">
         </form>
      </body>
        <script>
        if (!window.WebSocket && window.MozWebSocket)
            window.WebSocket = window.MozWebSocket;
        if (!window.WebSocket) {
            alert("此浏览器不支持WebSocket");
        }
        //创建WebSocket,location.host获得主机名+端口号
        var ws = new WebSocket("ws://" + location.host + "/websocket/websocket");
        //连接建立后调用的函数
        ws.onopen = function() {
            //将我们的form改变为可以输入的形式
            $("form *").attr("disabled", false);
        }
        //接受服务器传入的数据的处理
        ws.onmessage = function(event) {
            alert(event.data);
        }
        //点击提交按钮后调用的参数
        function echo() {
            ws.send($("#message").val());
        }
    </script>
    </html>

    (2)、java代码

    package com;
    
    import java.io.IOException;
    import java.util.concurrent.CopyOnWriteArraySet;
    
    import javax.websocket.OnClose;
    import javax.websocket.OnError;
    import javax.websocket.OnMessage;
    import javax.websocket.OnOpen;
    import javax.websocket.Session;
    import javax.websocket.server.ServerEndpoint;
    
    @ServerEndpoint("/websocket")  
    public class MyWebSocket {  
        //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。  
        private static int onlineCount = 0;  
           
        //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识  
        private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();  
           
        //与某个客户端的连接会话,需要通过它来给客户端发送数据  
        private Session session;  
           
        /** 
         * 连接建立成功调用的方法 
         * @param session  可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据 
         */  
        @OnOpen  
        public void onOpen(Session session){  
            this.session = session;  
            webSocketSet.add(this);     //加入set中  
            addOnlineCount();           //在线数加1  
            System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());  
        }  
           
        /** 
         * 连接关闭调用的方法 
         */  
        @OnClose  
        public void onClose(){  
            webSocketSet.remove(this);  //从set中删除  
            subOnlineCount();           //在线数减1      
            System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());  
        }  
           
        /** 
         * 收到客户端消息后调用的方法 
         * @param message 客户端发送过来的消息 
         * @param session 可选的参数 
         */  
        @OnMessage  
        public void onMessage(String message, Session session) {  
            System.out.println("来自客户端的消息:" + message);  
               
            //群发消息  
            for(MyWebSocket item: webSocketSet){               
                try {  
                    item.sendMessage(message);  
                } catch (IOException e) {  
                    e.printStackTrace();  
                    continue;  
                }  
            }  
        }  
           
        /** 
         * 发生错误时调用 
         * @param session 
         * @param error 
         */  
        @OnError  
        public void onError(Session session, Throwable error){  
            System.out.println("发生错误");  
            error.printStackTrace();  
        }  
           
        /** 
         * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。 
         * @param message 
         * @throws IOException 
         */  
        public void sendMessage(String message) throws IOException{  
            this.session.getBasicRemote().sendText(message);  
            //this.session.getAsyncRemote().sendText(message);  
        }  
       
        public static synchronized int getOnlineCount() {  
            return onlineCount;  
        }  
       
        public static synchronized void addOnlineCount() {  
            MyWebSocket.onlineCount++;  
        }  
           
        public static synchronized void subOnlineCount() {  
            MyWebSocket.onlineCount--;  
        }  
    } 
    

    (3).web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="2.5" 
        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_2_5.xsd">
      <display-name></display-name>
      <servlet>
        <description>This is the description of my J2EE component</description>
        <display-name>This is the display name of my J2EE component</display-name>
        <servlet-name>EchoServlet</servlet-name>
        <servlet-class>com.EchoServlet</servlet-class>
      </servlet>
      <servlet>
        <description>This is the description of my J2EE component</description>
        <display-name>This is the display name of my J2EE component</display-name>
        <servlet-name>MyWebSocket</servlet-name>
        <servlet-class>com.MyWebSocket</servlet-class>
      </servlet>
    
    
      <servlet-mapping>
        <servlet-name>EchoServlet</servlet-name>
        <url-pattern>/servlet/EchoServlet</url-pattern>
      </servlet-mapping>
      <servlet-mapping>
        <servlet-name>MyWebSocket</servlet-name>
        <url-pattern>/servlet/MyWebSocket</url-pattern>
      </servlet-mapping>    
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>

     相信大家好好体会代码,我也是花了一两个钟才做成这个例子的,然后就立刻给博客友写文章,喜欢和我交流可以加我的博客园

  • 相关阅读:
    purple-class2-默认选项切换
    purple-accessData
    “/wechat”应用程序中的服务器错误。
    GDI+ 中发生一般性错误。
    ylbtech-Unitity-CS:Indexers
    ylbtech-Unitity-CS:Hello world
    ylbtech-Unitity-CS:Generics
    ylbtech-Unitity-CS:Delegates
    ZooKeeper目录
    Zookeeper常用命令 (转)
  • 原文地址:https://www.cnblogs.com/imfjj/p/5813672.html
Copyright © 2020-2023  润新知