zoukankan      html  css  js  c++  java
  • java代码实现websocket前后端交互

    package socketTest;
    
    import java.util.Set;
    
    import javax.websocket.Endpoint;
    import javax.websocket.server.ServerApplicationConfig;
    import javax.websocket.server.ServerEndpointConfig;
    
    /**
     * 1, webSocket 的配置类, 需要实现接口 ServerApplicationConfig 
     * 2, webSocket 类在扫描到之后根据需要在实现的方法中进行一定的过滤, 返回过滤后的才能被前端访问
     * 3, getAnnotatedEndpointClasses 基于注解的 webSocket 扫描方法
     * 4, getEndpointConfigs 基于 XML 配置文件的的 webSocket 扫描方法
     */
    public class MyWbeSocketConfig implements ServerApplicationConfig {
        
       
        public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> webSockets) {
            return webSockets;
        }
        public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> arg0) {
            return null;
        }
    }
    

      

    package socketTest;
    
    import java.io.IOException;
    
    import javax.websocket.OnClose;
    import javax.websocket.OnMessage;
    import javax.websocket.OnOpen;
    import javax.websocket.Session;
    import javax.websocket.server.ServerEndpoint;
    
    /**
     * 1, WebSocket可以通过注解的方式声明  @ServerEndpoint("/WebSocket")
     * 2, 添加注解之后需要在配置文件中返回, 在配置文件中可以过滤
     * 3, WebSocket 和 Servlet 相同都是多列的, 不会互相干扰
     * 4, WebSocket 请求时访问 open  方法, 可以用注解 @OnOpen 标明
     * 5, WebSocket 关闭时访问 close 方法, 可以用注解 @OnClose 表名
     */
    @ServerEndpoint("/WebSocket")
    public class WebSocketDemo {
        @OnOpen
        public void open(Session session) {
            String id = session.getId();
            System.out.println("通道 " + id + " 打开");
        }
        
        @OnClose
        public void close (Session session) {
            String id = session.getId();
            try {
                session.getBasicRemote().sendText("客户端" + id + "关闭成功");
            } catch (IOException e) {
                System.out.println("客户端" + id + "关闭失败");
            }
        }
        
        @OnMessage
        public void message(Session session, String msg) {
            String outMessade = "客户端 " + session.getId() + " 说:" + msg;
            System.out.println(outMessade);
            String returnMessage = "你刚才说:" + msg;
            try {
                session.getBasicRemote().sendText(returnMessage);
            } catch (IOException e) {
                System.out.println("返回数据失败");
            }
         }
    }
    

      //html代码

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
        <title>WebSocket</title>
        <script type="text/javascript" src="js/jquery.min.js"></script>
    </head>
    <body>
        <input id="CreateSocket" type="button" value="创建WebSocKet" />
        <input id="Message" type="text" value=""/>
        <input id="Send" type="button" value="发送" />
        <input id="Close" type="button" value="关闭WebSocket" />
    </body>
    <script type="text/javascript">    
        /**
         * 创建 WebSocKet 的方法
         */
        function createWebSocket(urlValue){
            if("WebSocket" in window){
                return new WebSocket(urlValue);
            } 
            if ("MozWebSocket" in window){
                return new MozWebSocket(urlValue);
            }
            console.log("浏览器不支持 WebSocKet");
        }
        
        /**
         * 1, 创建WebSocket
         * 2, WebScoket 的地址为ws协议
         */
        var webSocket = null;
        var urlValue = "ws://localhost:8080/socket/WebSocket";
        
        $('#CreateSocket').on('click', function(){
            webSocket = createWebSocket(urlValue);
            // 服务器返回数据时执行
            webSocket.onmessage = function(msg){
                console.log(msg.data);
            }
            // 请求关闭时执行
            webSocket.onclose = function(){
                console.log(arguments);
            }
        });
        
        $('#Send').on('click', function(){
        	console.log("进入发送--------")
            var message = $('#Message').val().trim();
        	console.log("进入发送内容--------"+message);
            if(message == ""){
                console.error("发送的内容不能为空!");
                return;
            }
            if(webSocket == null){
                console.log("未创建 WebSocket 请求!");
                return;
            }
            // 向服务器发送请求的方法
            webSocket.send(message);
            console.log("message=============="+message);
            $('#Message').val("");
        });
        
        $('#Close').on('click', function(){
        	// 请求关闭时执行
            webSocket.onclose = function(){
                console.log(arguments);
            }
        });
    </script>
    

      pom.xml文件

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.cn</groupId>
      <artifactId>socket</artifactId>
      <version>0.0.1-SNAPSHOT</version>
      <packaging>war</packaging>
      <dependencies>
    		  <dependency>
    		    <groupId>javax.websocket</groupId>
    		    <artifactId>javax.websocket-api</artifactId>
    		    <version>1.1</version>
    		</dependency>
      </dependencies>
    </project>
    

      //创建一个maven项目打war包

     请求路径

     

  • 相关阅读:
    poj 3310(并查集判环,图的连通性,树上最长直径路径标记)
    poj 3308(最小点权覆盖、最小割)
    poj 3281(网络流+拆点)
    poj 3275(传递闭包)
    poj 3204(最小割)
    poj 3164(最小树形图)
    poj 2987(最大权闭合图+割边最少)
    poj 2455(二分+最大流)
    poj 2391(二分+最大流)
    poj 2135(最小费用最大流)
  • 原文地址:https://www.cnblogs.com/xianz666/p/14421417.html
Copyright © 2011-2022 走看看