Websocket ?

Тема в разделе "Java", создана пользователем Radion2, 23 фев 2013.

  1. Radion2

    Radion2 Member

    Регистрация:
    13 сен 2006
    Сообщения:
    23
    Симпатии:
    0
    TailorWebSocketServlet.java
    Код (Text):
    package de.devsurf.html.tail;

    import java.io.IOException;
    import java.util.Date;
    import java.util.Set;
    import java.util.concurrent.CopyOnWriteArraySet;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.TimeUnit;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    import org.eclipse.jetty.websocket.WebSocket;
    import org.eclipse.jetty.websocket.WebSocketServlet;

    public class TailorWebSocketServlet extends WebSocketServlet {
    private static final long serialVersionUID = -7289719281366784056L;
    public static String newLine = System.getProperty("line.separator");

    private final Set<TailorSocket> _members = new CopyOnWriteArraySet<TailorSocket>();
    private ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

    @Override
    public void init() throws ServletException {
    super.init();
    executor.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
    System.out.println("Running Server Message Sending");
    for(TailorSocket member : _members){
    System.out.println("Trying to send to Member!");
    if(member.isOpen()){
    System.out.println("Sending!");
    try {
    member.sendMessage("Sending a Message to you Guys! "+new Date()+newLine);
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    }
    }, 2, 2, TimeUnit.SECONDS);

    }

    protected void doGet(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
    getServletContext().getNamedDispatcher("default").forward(request,
    response);
    }

    public WebSocket doWebSocketConnect(HttpServletRequest request,
    String protocol) {
    return new TailorSocket();
    }

    class TailorSocket implements WebSocket.OnTextMessage {
    private Connection _connection;

    @Override
    public void onClose(int closeCode, String message) {
    _members.remove(this);
    }

    public void sendMessage(String data) throws IOException {
    _connection.sendMessage(data);
    }

    @Override
    public void onMessage(String data) {
    System.out.println("Received: "+data);
    }

    public boolean isOpen() {
    return _connection.isOpen();
    }

    @Override
    public void onOpen(Connection connection) {
    _members.add(this);
    _connection = connection;
    try {
    connection.sendMessage("Server received Web Socket upgrade and added it to Receiver List.");
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }
    }
    web.xml
    Код (Text):
    <?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>TailorWebSocketServlet</display-name>
    <servlet>
    <servlet-name>TailorWebSocketServlet</servlet-name>
    <servlet-class>de.devsurf.html.tail.TailorWebSocketServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>TailorWebSocketServlet</servlet-name>
    <url-pattern>/TailorWebSocketServlet</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
    <welcome-file>test.html</welcome-file>
    </welcome-file-list>
    </web-app>
    test.html
    Код (Text):
    <html>
    <head>
    <title>Tail-based by Web Sockets</title>
    <script type='text/javascript'>
    if (!window.WebSocket)
    alert("WebSocket not supported by this browser");

    function $() {
    return document.getElementById(arguments[0]);
    }
    function $F() {
    return document.getElementById(arguments[0]).value;
    }

    function getKeyCode(ev) {
    if (window.event)
    return window.event.keyCode;
    return ev.keyCode;
    }

    var server = {
    connect : function() {
    var location = document.location.toString().replace('http://',
    'ws://').replace('https://', 'wss://').replace('test.html','TailorWebSocketServlet'); //servlet/WebSocket
    alert(location);
    this._ws = new WebSocket(location);
    this._ws.onopen = this._onopen;
    this._ws.onmessage = this._onmessage;
    this._ws.onclose = this._onclose;
    },

    _onopen : function() {
    server._send('websockets are open for communications!');
    },

    _send : function(message) {
    if (this._ws)
    this._ws.send(message);
    },

    send : function(text) {
    if (text != null && text.length > 0)
    server._send(text);
    },

    _onmessage : function(m) {
    if (m.data) {
    var messageBox = $('messageBox');
    var spanText = document.createElement('span');
    spanText.className = 'text';
    spanText.innerHTML = m.data;
    var lineBreak = document.createElement('br');
    messageBox.appendChild(spanText);
    messageBox.appendChild(lineBreak);
    messageBox.scrollTop = messageBox.scrollHeight
    - messageBox.clientHeight;
    }
    },

    _onclose : function(m) {
    this._ws = null;
    }
    };
    </script>
    <style type='text/css'>
    div {
    border: 0px solid black;
    }

    div#messageBox {
    clear: both;
    width: 40em;
    height: 20ex;
    overflow: auto;
    background-color: #f0f0f0;
    padding: 4px;
    border: 1px solid black;
    }

    div#input {
    clear: both;
    width: 40em;
    padding: 4px;
    background-color: #e0e0e0;
    border: 1px solid black;
    border-top: 0px
    }

    div.hidden {
    display: none;
    }

    span.alert {
    font-style: italic;
    }
    </style>
    </head>
    <body>
    <div id='messageBox'></div>
    <div id='input'>
    <div>
    <input id='connect' class='button' type='submit' name='Connect'
    value='Connect' />
    </div>
    </div>
    <script type='text/javascript'>
    $('connect').onclick = function(event) {
    server.connect();
    return false;
    };
    </script>

    <p>
    This is a demonstration of the Jetty websocket server.
    </p>
    </body>
    </html>

    само решение с WebSocket взято отсюда https://gist.github.com/manzke/1021982

    использую XAMPP последнюю версию. вроде склько возился с сервлетами а на этот раз не получается. не пойму в чём причина.


    P.S.: я там в web.xml и в test.html только пути под себя подстроил. сторонняя библиотека взята вот эта jetty-websocket-8.0.1.v20110908.jar

    может кто может проверить об я пути в web.xml и в test.html правильно изменил(для XAMPP'а) ?
     

Поделиться этой страницей