一、前言
基于Undertow的io.undertow.Undertow、io.undertow.server、io.undertow.websockets定义后端简单ChatServer聊天服务器,并通过前端HTML基于的ws://通信协议的JS调用进行数据交互,详情参见代码示例部分(项目主要依赖xnio-api-3.3.0.Final.jar [更多其他版本]、xnio-nio-3.3.0.Final.jar包 [更多其他版本] )。
二、代码示例
1.ChatServer服务类
package test.undertow;@b@@b@import io.undertow.Undertow;@b@import io.undertow.server.handlers.resource.ClassPathResourceManager;@b@import io.undertow.websockets.WebSocketConnectionCallback;@b@import io.undertow.websockets.core.AbstractReceiveListener;@b@import io.undertow.websockets.core.BufferedTextMessage;@b@import io.undertow.websockets.core.WebSocketChannel;@b@import io.undertow.websockets.core.WebSockets;@b@import io.undertow.websockets.spi.WebSocketHttpExchange;@b@import static io.undertow.Handlers.path;@b@import static io.undertow.Handlers.resource;@b@import static io.undertow.Handlers.websocket;@b@@b@@UndertowExample("Chat")@b@public class ChatServer {@b@@b@ public static void main(final String[] args) {@b@@b@ System.out.println("To see chat in action is to open two different browsers and point them at http://localhost:8080");@b@@b@ Undertow server = Undertow.builder()@b@ .addHttpListener(8080, "localhost")@b@ .setHandler(path()@b@ .addPrefixPath("/myapp", websocket(new WebSocketConnectionCallback() {@b@@b@ @Override@b@ public void onConnect(WebSocketHttpExchange exchange, WebSocketChannel channel) {@b@ channel.getReceiveSetter().set(new AbstractReceiveListener() {@b@@b@ @Override@b@ protected void onFullTextMessage(WebSocketChannel channel, BufferedTextMessage message) {@b@ final String messageData = message.getData();@b@ for (WebSocketChannel session : channel.getPeerConnections()) {@b@ WebSockets.sendText(messageData, session, null);@b@ }@b@ System.out.println("message event data -------------------------:"+messageData);@b@ }@b@ });@b@ channel.resumeReceives();@b@ }@b@@b@ }))@b@ .addPrefixPath("/", resource(new ClassPathResourceManager(ChatServer.class.getClassLoader(), ChatServer.class.getPackage()))@b@ .addWelcomeFiles("index.html")))@b@ .build();@b@@b@ server.start();@b@ }@b@@b@}
package test.undertow;@b@@b@import java.lang.annotation.ElementType;@b@import java.lang.annotation.Retention;@b@import java.lang.annotation.RetentionPolicy;@b@import java.lang.annotation.Target;@b@@b@ @b@@Retention(RetentionPolicy.RUNTIME)@b@@Target(ElementType.TYPE)@b@public @interface UndertowExample {@b@ String value();@b@ String location() default "http://localhost:8080";@b@}
2.前端H5对应JS调用代码
<!--@b@ ~ JBoss, Home of Professional Open Source.@b@ ~ Copyright 2014 Red Hat, Inc., and inpidual contributors@b@ ~ as indicated by the @author tags.@b@ ~@b@ ~ Licensed under the Apache License, Version 2.0 (the "License");@b@ ~ you may not use this file except in compliance with the License.@b@ ~ You may obtain a copy of the License at@b@ ~@b@ ~ http://www.apache.org/licenses/LICENSE-2.0@b@ ~@b@ ~ Unless required by applicable law or agreed to in writing, software@b@ ~ distributed under the License is distributed on an "AS IS" BASIS,@b@ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.@b@ ~ See the License for the specific language governing permissions and@b@ ~ limitations under the License.@b@ -->@b@@b@<html>@b@<head><title>Undertow Chat</title>@b@<script>@b@ var socket;@b@ if (window.WebSocket) {@b@ socket = new WebSocket("ws://localhost:8080/myapp");@b@ socket.onmessage = function (event) {@b@ var chat = document.getElementById('chat');@b@ chat.innerHTML = chat.innerHTML + event.data + "<br />";@b@ };@b@ } else {@b@ alert("Your browser does not support Websockets. (Use Chrome)");@b@ }@b@@b@ function send(message) {@b@ if (!window.WebSocket) {@b@ return false;@b@ }@b@ if (socket.readyState == WebSocket.OPEN) {@b@ socket.send(message);@b@ } else {@b@ alert("The socket is not open.");@b@ }@b@ return false;@b@ }@b@</script>@b@<style type="text/css">@b@ html,body {width:100%;height:100%;}@b@ html,body,ul,ol,dl,li,dt,dd,p,blockquote,fieldset,legend,img,form,h1,h2,h3,h4,h5,h6 {margin:0;padding:0;}@b@ body {@b@ font:normal 12px/1.5 Arial,Helvetica,'Bitstream Vera Sans',sans-serif;@b@ background: #c5deea; /* Old browsers */@b@ background: -moz-linear-gradient(top, #c5deea 0%, #066dab 100%); /* FF3.6+ */@b@ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #c5deea), color-stop(100%, #066dab)); /* Chrome,Safari4+ */@b@ background: -webkit-linear-gradient(top, #c5deea 0%, #066dab 100%); /* Chrome10+,Safari5.1+ */@b@ background: -o-linear-gradient(top, #c5deea 0%, #066dab 100%); /* Opera 11.10+ */@b@ background: -ms-linear-gradient(top, #c5deea 0%, #066dab 100%); /* IE10+ */@b@ background: linear-gradient(to bottom, #c5deea 0%, #066dab 100%); /* W3C */@b@ height: 90%;@b@ }@b@@b@ .center {@b@ margin-left: auto;@b@ margin-right: auto;@b@ width: 70%;@b@ background: white;@b@ }@b@@b@ .chatform {@b@ margin-left: auto;@b@ margin-right: auto;@b@ margin-bottom: 0;@b@ width: 70%;@b@ }@b@ form{@b@ width: 100%;@b@ }@b@ label{@b@ display: inline;@b@ width: 100px;@b@ }@b@ #msg{@b@ display: inline;@b@ width: 100%;@b@ }@b@@b@</style>@b@</head>@b@<body>@b@<p class="page">@b@ <p class="center" >@b@ <h1>Web Socket Chat</h1>@b@ <p id="chat" style="height:100%;width: 100%; overflow: scroll;">@b@@b@@b@ </p>@b@@b@ <form onsubmit="return false;" class="chatform" action="">@b@ <label for="msg">Message</label>@b@ <input type="text" name="message" id="msg" onkeypress="if(event.keyCode==13) { send(this.form.message.value); this.value='' } " />@b@ </form>@b@ </p>@b@</p>@b@</body>@b@</html>
3.测试运行效果如下图所示