View | Details | Raw Unified | Return to bug 51181
Collapse All | Expand All

(-)webapps/examples/WEB-INF/classes/websocket/snake/SnakeWebSocketServlet.java (-2 / +2 lines)
Lines 98-105 Link Here
98
    private void broadcast(String message) {
98
    private void broadcast(String message) {
99
        for (SnakeMessageInbound connection : getConnections()) {
99
        for (SnakeMessageInbound connection : getConnections()) {
100
            try {
100
            try {
101
                CharBuffer response = CharBuffer.wrap(message);
101
                CharBuffer buffer = CharBuffer.wrap(message);
102
                connection.getWsOutbound().writeTextMessage(response);
102
                connection.getWsOutbound().writeTextMessage(buffer);
103
            } catch (IOException ignore) {
103
            } catch (IOException ignore) {
104
                // Ignore
104
                // Ignore
105
            }
105
            }
(-)webapps/examples/websocket/snake.html (-2 / +2 lines)
Lines 51-58 Link Here
51
    </style>
51
    </style>
52
</head>
52
</head>
53
<body>
53
<body>
54
    <noscript><h1>Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable
54
    <noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable
55
    Javascript and reload this page!</h1></noscript>
55
    Javascript and reload this page!</h2></noscript>
56
    <div style="float: left">
56
    <div style="float: left">
57
        <canvas id="playground" width="640" height="480"></canvas>
57
        <canvas id="playground" width="640" height="480"></canvas>
58
    </div>
58
    </div>
(-)webapps/examples/WEB-INF/web.xml (-2 / +10 lines)
Lines 350-356 Link Here
350
    <!-- WebSocket Examples -->
350
    <!-- WebSocket Examples -->
351
    <servlet>
351
    <servlet>
352
      <servlet-name>wsEchoStream</servlet-name>
352
      <servlet-name>wsEchoStream</servlet-name>
353
      <servlet-class>websocket.EchoStream</servlet-class>
353
      <servlet-class>websocket.echo.EchoStream</servlet-class>
354
    </servlet>
354
    </servlet>
355
    <servlet-mapping>
355
    <servlet-mapping>
356
      <servlet-name>wsEchoStream</servlet-name>
356
      <servlet-name>wsEchoStream</servlet-name>
Lines 358-364 Link Here
358
    </servlet-mapping>
358
    </servlet-mapping>
359
    <servlet>
359
    <servlet>
360
      <servlet-name>wsEchoMessage</servlet-name>
360
      <servlet-name>wsEchoMessage</servlet-name>
361
      <servlet-class>websocket.EchoMessage</servlet-class>
361
      <servlet-class>websocket.echo.EchoMessage</servlet-class>
362
      <!-- Uncomment the following block to increase the default maximum
362
      <!-- Uncomment the following block to increase the default maximum
363
           WebSocket buffer size from 2MB to 20MB which is required for the
363
           WebSocket buffer size from 2MB to 20MB which is required for the
364
           Autobahn test suite to pass fully. -->
364
           Autobahn test suite to pass fully. -->
Lines 376-381 Link Here
376
    <servlet-mapping>
376
    <servlet-mapping>
377
      <servlet-name>wsEchoMessage</servlet-name>
377
      <servlet-name>wsEchoMessage</servlet-name>
378
      <url-pattern>/websocket/echoMessage</url-pattern>
378
      <url-pattern>/websocket/echoMessage</url-pattern>
379
    </servlet-mapping>
380
    <servlet>
381
        <servlet-name>wsChat</servlet-name>
382
        <servlet-class>websocket.chat.ChatWebSocketServlet</servlet-class>
383
    </servlet>
384
    <servlet-mapping>
385
        <servlet-name>wsChat</servlet-name>
386
        <url-pattern>/websocket/chat</url-pattern>
379
    </servlet-mapping>
387
    </servlet-mapping>
380
    <servlet>
388
    <servlet>
381
      <servlet-name>wsSnake</servlet-name>
389
      <servlet-name>wsSnake</servlet-name>
(-)webapps/examples/WEB-INF/classes/websocket/snake/Snake.java (-1 / +11 lines)
Lines 93-106 Link Here
93
            head = nextLocation;
93
            head = nextLocation;
94
        }
94
        }
95
95
96
        handleCollisions(snakes);
97
    }
98
99
    private void handleCollisions(Collection<Snake> snakes) {
96
        for (Snake snake : snakes) {
100
        for (Snake snake : snakes) {
97
            if (snake.getTail().contains(head)) {
101
            boolean headCollision = id != snake.id && snake.getHead().equals(head);
102
            boolean tailCollision = snake.getTail().contains(head);
103
            if (headCollision || tailCollision) {
98
                kill();
104
                kill();
99
                if (id != snake.id) {
105
                if (id != snake.id) {
100
                    snake.reward();
106
                    snake.reward();
101
                }
107
                }
102
            }
108
            }
103
        }
109
        }
110
    }
111
112
    public synchronized Location getHead() {
113
        return head;
104
    }
114
    }
105
115
106
    public synchronized Collection<Location> getTail() {
116
    public synchronized Collection<Location> getTail() {
(-)webapps/examples/WEB-INF/classes/websocket/chat/ChatWebSocketServlet.java (+99 lines)
Line 0 Link Here
1
/*
2
 * Licensed to the Apache Software Foundation (ASF) under one or more
3
 * contributor license agreements.  See the NOTICE file distributed with
4
 * this work for additional information regarding copyright ownership.
5
 * The ASF licenses this file to You under the Apache License, Version 2.0
6
 * (the "License"); you may not use this file except in compliance with
7
 * the License.  You may obtain a copy of the License at
8
 *
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 *
11
 * Unless required by applicable law or agreed to in writing, software
12
 * distributed under the License is distributed on an "AS IS" BASIS,
13
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
16
 */
17
package websocket.chat;
18
19
import org.apache.catalina.websocket.MessageInbound;
20
import org.apache.catalina.websocket.StreamInbound;
21
import org.apache.catalina.websocket.WebSocketServlet;
22
import org.apache.catalina.websocket.WsOutbound;
23
import util.HTMLFilter;
24
25
import java.io.IOException;
26
import java.nio.ByteBuffer;
27
import java.nio.CharBuffer;
28
import java.util.Set;
29
import java.util.concurrent.CopyOnWriteArraySet;
30
import java.util.concurrent.atomic.AtomicInteger;
31
32
/**
33
 * Example web socket servlet for chat.
34
 */
35
public class ChatWebSocketServlet extends WebSocketServlet {
36
37
    private static final long serialVersionUID = 1L;
38
39
    private static final String GUEST_PREFIX = "Guest";
40
41
    private final AtomicInteger connectionIds = new AtomicInteger(0);
42
    private final Set<ChatMessageInbound> connections =
43
            new CopyOnWriteArraySet<ChatMessageInbound>();
44
45
    @Override
46
    protected StreamInbound createWebSocketInbound(String subProtocol) {
47
        return new ChatMessageInbound(connectionIds.incrementAndGet());
48
    }
49
50
    private final class ChatMessageInbound extends MessageInbound {
51
52
        private final String nickname;
53
54
        private ChatMessageInbound(int id) {
55
            this.nickname = GUEST_PREFIX + id;
56
        }
57
58
        @Override
59
        protected void onOpen(WsOutbound outbound) {
60
            connections.add(this);
61
            String message = String.format("* %s %s",
62
                    nickname, "has joined.");
63
            broadcast(message);
64
        }
65
66
        @Override
67
        protected void onClose(int status) {
68
            connections.remove(this);
69
            String message = String.format("* %s %s",
70
                    nickname, "has disconnected.");
71
            broadcast(message);
72
        }
73
74
        @Override
75
        protected void onBinaryMessage(ByteBuffer message) throws IOException {
76
            throw new UnsupportedOperationException(
77
                    "Binary message not supported.");
78
        }
79
80
        @Override
81
        protected void onTextMessage(CharBuffer message) throws IOException {
82
            // Never trust the client
83
            String filteredMessage = String.format("%s: %s",
84
                    nickname, HTMLFilter.filter(message.toString()));
85
            broadcast(filteredMessage);
86
        }
87
88
        private void broadcast(String message) {
89
            for (ChatMessageInbound connection : connections) {
90
                try {
91
                    CharBuffer buffer = CharBuffer.wrap(message);
92
                    connection.getWsOutbound().writeTextMessage(buffer);
93
                } catch (IOException ignore) {
94
                    // Ignore
95
                }
96
            }
97
        }
98
    }
99
}
(-)webapps/examples/websocket/echo.html (-3 / +3 lines)
Lines 30-36 Link Here
30
30
31
        #console-container {
31
        #console-container {
32
            float: left;
32
            float: left;
33
            padding-left: 20px;
33
            margin-left: 15px;
34
            width: 400px;
34
            width: 400px;
35
        }
35
        }
36
36
Lines 121-128 Link Here
121
    </script>
121
    </script>
122
</head>
122
</head>
123
<body>
123
<body>
124
<noscript><h1>Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable
124
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable
125
    Javascript and reload this page!</h1></noscript>
125
    Javascript and reload this page!</h2></noscript>
126
<div>
126
<div>
127
    <div id="connect-container">
127
    <div id="connect-container">
128
        <div>
128
        <div>
(-)webapps/examples/WEB-INF/classes/websocket/EchoMessage.java (-1 / +1 lines)
Lines 14-20 Link Here
14
 * See the License for the specific language governing permissions and
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
15
 * limitations under the License.
16
 */
16
 */
17
package websocket;
17
package websocket.echo;
18
18
19
import java.io.IOException;
19
import java.io.IOException;
20
import java.nio.ByteBuffer;
20
import java.nio.ByteBuffer;
(-)webapps/examples/websocket/chat.html (+121 lines)
Line 0 Link Here
1
<!--
2
  Licensed to the Apache Software Foundation (ASF) under one or more
3
  contributor license agreements.  See the NOTICE file distributed with
4
  this work for additional information regarding copyright ownership.
5
  The ASF licenses this file to You under the Apache License, Version 2.0
6
  (the "License"); you may not use this file except in compliance with
7
  the License.  You may obtain a copy of the License at
8
9
      http://www.apache.org/licenses/LICENSE-2.0
10
11
  Unless required by applicable law or agreed to in writing, software
12
  distributed under the License is distributed on an "AS IS" BASIS,
13
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
  See the License for the specific language governing permissions and
15
  limitations under the License.
16
-->
17
<!DOCTYPE html>
18
<html>
19
<head>
20
    <title>Apache Tomcat WebSocket Examples: Chat</title>
21
    <style type="text/css">
22
        input#chat {
23
            width: 410px
24
        }
25
26
        #console-container {
27
            width: 400px;
28
        }
29
30
        #console {
31
            border: 1px solid #CCCCCC;
32
            border-right-color: #999999;
33
            border-bottom-color: #999999;
34
            height: 170px;
35
            overflow-y: scroll;
36
            padding: 5px;
37
            width: 100%;
38
        }
39
40
        #console p {
41
            padding: 0;
42
            margin: 0;
43
        }
44
    </style>
45
    <script type="text/javascript">
46
        var Chat = {};
47
48
        Chat.socket = null;
49
50
        Chat.connect = (function(host) {
51
            if ('WebSocket' in window) {
52
                Chat.socket = new WebSocket(host);
53
            } else if ('MozWebSocket' in window) {
54
                Chat.socket = new MozWebSocket(host);
55
            } else {
56
                Console.log('Error: WebSocket is not supported by this browser.');
57
                return;
58
            }
59
60
            Chat.socket.onopen = function () {
61
                Console.log('Info: WebSocket connection opened.');
62
                document.getElementById('chat').onkeydown = function(event) {
63
                    if (event.keyCode == 13) {
64
                        Chat.sendMessage();
65
                    }
66
                };
67
            };
68
69
            Chat.socket.onclose = function () {
70
                document.getElementById('chat').onkeydown = null;
71
                Console.log('Info: WebSocket closed.');
72
            };
73
74
            Chat.socket.onmessage = function (message) {
75
                Console.log(message.data);
76
            };
77
        });
78
79
        Chat.initialize = function() {
80
            Chat.connect('ws://' + window.location.host + '/examples/websocket/chat');
81
        };
82
83
        Chat.sendMessage = (function() {
84
            var message = document.getElementById('chat').value;
85
            if (message != '') {
86
                Chat.socket.send(message);
87
                document.getElementById('chat').value = '';
88
            }
89
        });
90
91
        var Console = {};
92
93
        Console.log = (function(message) {
94
            var console = document.getElementById('console');
95
            var p = document.createElement('p');
96
            p.style.wordWrap = 'break-word';
97
            p.innerHTML = message;
98
            console.appendChild(p);
99
            while (console.childNodes.length > 25) {
100
                console.removeChild(console.firstChild);
101
            }
102
            console.scrollTop = console.scrollHeight;
103
        });
104
105
        Chat.initialize();
106
107
    </script>
108
</head>
109
<body>
110
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable
111
    Javascript and reload this page!</h2></noscript>
112
<div>
113
    <p>
114
        <input type="text" placeholder="type and press enter to chat" id="chat">
115
    </p>
116
    <div id="console-container">
117
        <div id="console"></div>
118
    </div>
119
</div>
120
</body>
121
</html>
(-)webapps/examples/WEB-INF/classes/websocket/EchoStream.java (-1 / +1 lines)
Lines 14-20 Link Here
14
 * See the License for the specific language governing permissions and
14
 * See the License for the specific language governing permissions and
15
 * limitations under the License.
15
 * limitations under the License.
16
 */
16
 */
17
package websocket;
17
package websocket.echo;
18
18
19
import java.io.IOException;
19
import java.io.IOException;
20
import java.io.InputStream;
20
import java.io.InputStream;
(-)webapps/examples/websocket/index.html (-10 / +12 lines)
Lines 15-29 Link Here
15
  limitations under the License.
15
  limitations under the License.
16
-->
16
-->
17
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
17
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
18
<HTML><HEAD><TITLE>Apache Tomcat WebSocket Examples</TITLE>
18
<html>
19
<META http-equiv=Content-Type content="text/html">
19
<head>
20
</HEAD>
20
    <meta http-equiv=Content-Type content="text/html">
21
<BODY>
21
    <title>Apache Tomcat WebSocket Examples</title>
22
<P>
22
</head>
23
<H3>Apache Tomcat WebSocket Examples</H3>
23
<body>
24
<P></P>
24
<h3>Apache Tomcat WebSocket Examples</h3>
25
<ul>
25
<ul>
26
<li><a href="echo.html">Echo example</a></li>
26
    <li><a href="echo.html">Echo example</a></li>
27
    <li><a href="chat.html">Chat example</a></li>
27
<li><a href="snake.html">Multiplayer snake example</a></li>
28
    <li><a href="snake.html">Multiplayer snake example</a></li>
28
</ul>
29
</ul>
29
</BODY></HTML>
30
</body>
31
</html>

Return to bug 51181