web socket

来源:互联网 发布:天勤行情数据怎么样 编辑:程序博客网 时间:2024/06/10 01:18


xhtml web page

<?xml version="1.0" encoding="UTF-8"?>


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Web Socket Test</title>
    <style type="text/css"><![CDATA[
        #console-container {
            width: 400px;
        }


        #console {
            border: 1px solid #CCCCCC;
            border-right-color: #999999;
            border-bottom-color: #999999;
            height: 170px;
            overflow-y: scroll;
            padding: 5px;
            width: 100%;
        }


        #console p {
            padding: 0;
            margin: 0;
        }
    ]]></style>
    <script type="application/javascript"><![CDATA[
        var Chat = {};


        Chat.socket = null;


        Chat.connect = (function(host) {
            if ('WebSocket' in window) {
                Chat.socket = new WebSocket(host);
            } else if ('MozWebSocket' in window) {
                Chat.socket = new MozWebSocket(host);
            } else {
                Console.log('Error: WebSocket is not supported by this browser.');
                return;
            }


            Chat.socket.onopen = function () {
            };


            Chat.socket.onclose = function () {
            };


            Chat.socket.onmessage = function (message) {
                Console.log(message.data);
            };
        });


        Chat.initialize = function() {
            if (window.location.protocol == 'http:') {
               Chat.connect('ws://' + window.location.host + '/JavaWebApp20140310/websocket/chat');
            } else {
                Chat.connect('wss://' + window.location.host + '/JavaWebApp20140310/websocket/chat');
            }
        };


        Chat.sendMessage = (function() {
        });


        var Console = {};


        Console.log = (function(message) {
            var console = document.getElementById('console');
            var p = document.createElement('p');
            p.style.wordWrap = 'break-word';
            p.innerHTML = message;
            console.appendChild(p);
            while (console.childNodes.length > 25) {
                console.removeChild(console.firstChild);
            }
            console.scrollTop = console.scrollHeight;
        });


        Chat.initialize();


        document.addEventListener("DOMContentLoaded", function() {
            // Remove elements with "noscript" class - <noscript> is not allowed in XHTML
            var noscripts = document.getElementsByClassName("noscript");
            for (var i = 0; i < noscripts.length; i++) {
                noscripts[i].parentNode.removeChild(noscripts[i]);
            }
        }, false);


    ]]></script>
</head>
<body>
<div class="noscript"><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable
    Javascript and reload this page!</h2></div>
<div>
    <div id="console-container">
        <div id="console"/>
    </div>
</div>
</body>
</html>



java code:

package websocket.chat;



import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;


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(value = "/websocket/chat")
public class ChatAnnotation {


    private static final AtomicInteger connectionIds = new AtomicInteger(0);
    private static final Set<ChatAnnotation> connections =
            new CopyOnWriteArraySet<ChatAnnotation>();


    private Session session;


    public ChatAnnotation() {
        
    }




    @OnOpen
    public void start(Session session) {
        
        this.session = session;
        connections.add(this);
        
        System.out.println("############## start ###################");
        
        broadcast("Start now......");
        
            
    }




    @OnClose
    public void end() {
        System.out.println("############## end ###################");
    }




    @OnMessage
    public void incoming(String message) {
        
            broadcast("incoming messages......");
    }
  
    
    @OnError
    public void onError(Throwable t) throws Throwable {
    }




    private static void broadcast(String msg) {
        if (msg == null)
            msg = "msg error in broadcast!!!";
        for (ChatAnnotation client : connections) {
            try {
                synchronized (client) {
                    client.session.getBasicRemote().sendText(msg);
                }      
                
               // client.session.getBasicRemote().sendText(client.session.getId());
            } catch (IOException e) {
                connections.remove(client);
                try {
                    client.session.close();
                } catch (IOException e1) {
                    // Ignore
                }
            }
        }
    }
}
0 0
原创粉丝点击