首页  |  知识库  |  资源下载  |  在线工具  |  A-Z  •  JAR  •  名词查         

基于Undertow的WebSocket通过前端JS调用定义WebSocketServer服务进行数据交互的代码示例

标签:undertow,WebSocket,websockets,代码例子,window.WebSocket     发布时间:2018-05-07   

一、前言

基于Undertow的io.undertow.websockets定义后端简单WebSocketServer服务,实现了前端HTML基于的ws://通信协议的JS调用进行数据交互,详情参见代码示例部分(项目主要依赖xnio-api-3.3.0.Final.jar [更多其他版本]、xnio-nio-3.3.0.Final.jar包 [更多其他版本] )。

二、代码示例

1.WebSocketServer服务类

package test;@b@@b@import io.undertow.Undertow;@b@import test.UndertowExample;@b@import io.undertow.server.handlers.resource.ClassPathResourceManager;@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.WebSocketConnectionCallback;@b@import io.undertow.websockets.spi.WebSocketHttpExchange;@b@@b@import static io.undertow.Handlers.path;@b@import static io.undertow.Handlers.resource;@b@import static io.undertow.Handlers.websocket;@b@@b@@UndertowExample("Web Sockets")@b@public class WebSocketServer {@b@@b@    public static void main(final String[] args) {@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@                                        String messageData=message.getData();@b@                                        WebSockets.sendText(messageData, channel, null);@b@                                        System.out.println("message event data -------------------------:"+messageData);@b@                                    }@b@                                    @b@                                });@b@                                channel.resumeReceives();@b@                            }@b@                            @b@                            @b@                            @b@                            @b@                        }))@b@                        .addPrefixPath("/", resource(new ClassPathResourceManager(WebSocketServer.class.getClassLoader(), WebSocketServer.class.getPackage())).addWelcomeFiles("index.html")))@b@                .build();@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调用代码

<html>@b@<head><title>Web Socket Test</title></head>@b@<body>@b@<script>@b@    var socket;@b@    if (window.WebSocket) {@b@        socket = new WebSocket("ws://localhost:8080/myapp");@b@        socket.onmessage = function(event) {@b@            alert("Received data from websocket: " + event.data);@b@        };@b@        socket.onopen = function(event) {@b@            alert("Web Socket opened!");@b@        };@b@        socket.onclose = function(event) {@b@            alert("Web Socket closed.");@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;@b@        }@b@        if (socket.readyState == WebSocket.OPEN) {@b@            socket.send(message);@b@        } else {@b@            alert("The socket is not open.");@b@        }@b@    }@b@</script>@b@<form onsubmit="return false;">@b@    <input type="text" name="message" value="Hello, World!"/>@b@    <input type="button" value="Send Web Socket Data" onclick="send(this.form.message.value)"/>@b@</form>@b@</body>@b@</html>

3.测试运行效果如下图所示

基于Undertow的WebSocket通过前端JS调用定义WebSocketServer服务进行数据交互的代码示例