• jdk6使用WebSocket


    pom.xml

    <dependency>
        <groupId>org.java-websocket</groupId>
        <artifactId>Java-WebSocket</artifactId>
        <version>1.3.4</version>
    </dependency>
    

      

    SimpleWebSocketServer.java

    package com.geostar.gfstack.operationcenter.common.util;
    
    import com.geostar.gfstack.framework.log.common.GeoLogger;
    import com.geostar.gfstack.operationcenter.common.properties.ConfigGeoStar;
    import org.java_websocket.WebSocket;
    import org.java_websocket.handshake.ClientHandshake;
    import org.java_websocket.server.WebSocketServer;
    
    import java.net.InetSocketAddress;
    import java.net.UnknownHostException;
    import java.util.Collection;
    
    public class SimpleWebSocketServer extends WebSocketServer {
    
        private static GeoLogger logger = GeoLogger.getLogger(SimpleWebSocketServer.class);
    
        private static SimpleWebSocketServer instance;
    
        public static final Integer port = ConfigGeoStar.getWebSocketPort();
    
        @Override
        public void onOpen(WebSocket conn, ClientHandshake handshake) {
            logger.info("Server open!");
        }
    
        @Override
        public void onClose(WebSocket conn, int code, String reason, boolean remote) {
            logger.info("Server closed!");
        }
    
        @Override
        public void onMessage(WebSocket conn, String message) {
            this.sendToAll(message);
        }
    
        @Override
        public void onError(WebSocket conn, Exception e) {
            logger.error(e.getMessage(), e);
        }
    
        @Override
        public void onStart() {
            logger.info("Server started!");
        }
    
        public void sendToAll(String text) {
            Collection<WebSocket> con = connections();
            synchronized (con) {
                for (WebSocket c : con) {
                    c.send(text);
                }
            }
        }
    
        private SimpleWebSocketServer() {
            super();
            try {
                SimpleWebSocketServer s = new SimpleWebSocketServer(port);
                s.start();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }
    
        private SimpleWebSocketServer(int port) throws UnknownHostException {
            super(new InetSocketAddress(port));
        }
    
        public synchronized static SimpleWebSocketServer getInstance() {
            if (instance == null) {
                instance = new SimpleWebSocketServer();
            }
            return instance;
        }
    
    }
    

      

    SimpleWebSocketClient.java

    package com.geostar.gfstack.operationcenter.common.util;
    
    import com.geostar.gfstack.framework.log.common.GeoLogger;
    import org.java_websocket.client.WebSocketClient;
    import org.java_websocket.drafts.Draft;
    import org.java_websocket.handshake.ServerHandshake;
    
    import java.net.URI;
    
    public class SimpleWebSocketClient extends WebSocketClient {
    
        private static GeoLogger logger = GeoLogger.getLogger(SimpleWebSocketClient.class);
    
        public SimpleWebSocketClient(URI serverUri, Draft protocolDraft) {
            super(serverUri, protocolDraft);
        }
    
        @Override
        public void onOpen(ServerHandshake serverHandshake) {
            logger.info("Client open!");
        }
    
        @Override
        public void onMessage(String s) {
            logger.info("Client message:"+s);
        }
    
        @Override
        public void onClose(int i, String s, boolean b) {
            logger.info("Client onClose!");
        }
    
        @Override
        public void onError(Exception e) {
            logger.error(e.getMessage(), e);
        }
    
    }
    

      

    前端js用法:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script type="text/javascript" src="../staticresource/fe-lib/websocket/web_socket.js"></script>
    
        <script type="text/javascript">
    
            // Write your code in the same way as for native WebSocket:
            var ws = new WebSocket('ws://192.168.30.174:8887')
            ws.onopen = function() {
                console.log('open')
                ws.send('Hello')  // Sends a message.
            }
            ws.onmessage = function(e) {
                // Receives a message.
                console.log(e.data);
            }
            ws.onclose = function() {
                console.log('close')
            }
    
        </script>
    </head>
    <body>
    
    </body>
    </html>
    

      

    java客户端用法:

    SimpleWebSocketServer.getInstance();
    URI uri = null;
    WebSocketClient client = null;
    try {
    	uri = new URI("ws://localhost:" + SimpleWebSocketServer.port);
    } catch (URISyntaxException e) {
    	e.printStackTrace();
    }
    if(uri != null){
    	client = new SimpleWebSocketClient(uri, new Draft_6455());
    	client.connect();
    }
    if(client != null){
    	client.send("hello java");
    }
    

      

    web_socket.js

  • 相关阅读:
    HDU4652 Dice
    CF113D Museum / BZOJ3270 博物馆
    SHOI2013 超级跳马
    最基本的卷积与反演
    NOI2014 动物园题解
    SP11414 COT3
    new to do
    linux C++中宏定义的问题:error: unable to find string literal operator ‘operator""fmt’ with ‘const char [4]’, ‘long unsigned int’ arguments
    新装vs2010的问题:fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
    windows下删除虚拟串口的方法,以及解决串口使用中,无法变更设备串口号的问题
  • 原文地址:https://www.cnblogs.com/nihaorz/p/7478160.html
Copyright © 2020-2023  润新知