使用Spark框架创建WebSocket服务器

w ^ebSocket is a protocol which enables communication between the server and the browser. It has an advantage over RESTful HTTP because communications are both bi-directional and real-time. This allows for the server to notify the client at any time instead of the client polling on a regular interval for updates.

In this series of posts, I'm going to show you three different ways to create a WebSocket server in Java using Spring Boot, the Spark Framework, and the Java AP一世 for WebSockets.

Prerequisites

You will be using Gradle to manage your dependencies and run your application.

此外,您需要确保已安装JDK的副本。 在本教程中,我将使用JDK 8。

WebSockets with the Spark Framework

小号park is a micro framework for creating Java and Kotlin web applications.

Create the Project

您将使用Gradle初始化新的Java应用程序。 您可以使用以下命令为您的项目创建目录,导航到该目录并初始化应用程序:

mkdir websocket-spark-framework
cd websocket-spark-framework
gradle init --type=java-application

Add the Spark Dependency

将以下依赖项添加到依存关系的块build.gradle:

compile 'com.sparkjava:spark-core:2.7.2'

Unlike Creating a WebSocket Server with Spring Boot, WebSockets with Spark only work with the embedded Jetty server, and you will need to define the path and the handler before any HTTP routes.

Create the WebSocket Handler

WebSocket消息可以是文本,也可以是二进制。 您将创建一个可以处理这两个消息的处理程序。

创建一个名为WebSocketHandler并用@WebSocket:

import org.eclipse.jetty.websocket.api.annotations.WebSocket;

@WebSocket
public class WebSocketHandler {

}

每个事件WebSocketHandler句柄由注释定义。 您可以使用@OnWebSocketMessage标记标记方法以接收二进制或文本事件。

出于演示目的,您将创建一个回显服务器,该服务器将把收到的消息回显给发件人。

添加以下方法:

@OnWebSocketMessage
public void handleTextMessage(Session session, String message) throws IOException {
    System.out.println("New Text Message Received");
    session.getRemote().sendString(message);
}

@OnWebSocketMessage
public void handleBinaryMessage(Session session, byte[] buffer, int offset, int length) throws IOException {
    System.out.println("New Binary Message Received");
    session.getRemote().sendBytes(ByteBuffer.wrap(buffer));
}

Note that the method signature determines which type of message the method will handle. See the OnWebSocketMessage annotation documentation for a list of supported method signatures.

Register the WebSocket Handler

为了使用WebSocketHandler,必须注册。

打开应用程式Gradle为您创建的课程。 删除getGreeting方法和内容主要方法,因为您都不需要。

在main方法内部,添加以下内容以注册WebSocketHandler在/插座路径:

@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    webSocket("/socket", WebSocketHandler.class);
}

Create a Client to Test Your Application

您将需要创建一个客户端来测试您的WebSocket服务器。 您将需要测试同时发送文本消息和二进制消息。 这可以用JavaScript完成。

创建资源里面的文件夹src / main夹。 里面的资源文件夹,创建静态的夹。

将以下内容添加到index.html在里面src / main / resources / static夹:

<html>
<head>
    <style>
        #messages {
            text-align: left;
            width: 50%;
            padding: 1em;
            border: 1px solid black;
        }
    </style>
    <title>Sample WebSocket Client</title>
</head>
<body>
<div class="container">
    <div id="messages" class="messages"></div>
    <div class="input-fields">
        <p>Type a message and hit send:</p>
        <input id="message"/>
        <button id="send">Send</button>

        <p>Select an image and hit send:</p>
        <input type="file" id="file" accept="image/*"/>

        <button id="sendImage">Send Image</button>
    </div>
</div>
</body>
<script>
    const messageWindow = document.getElementById("messages");

    const sendButton = document.getElementById("send");
    const messageInput = document.getElementById("message");

    const fileInput = document.getElementById("file");
    const sendImageButton = document.getElementById("sendImage");

    const socket = new WebSocket("ws://localhost:8080/socket");
    socket.binaryType = "arraybuffer";

    socket.onopen = function (event) {
        addMessageToWindow("Connected");
    };

    socket.onmessage = function (event) {
        if (event.data instanceof ArrayBuffer) {
            addMessageToWindow('Got Image:');
            addImageToWindow(event.data);
        } else {
            addMessageToWindow(`Got Message: ${event.data}`);
        }
    };

    sendButton.onclick = function (event) {
        sendMessage(messageInput.value);
        messageInput.value = "";
    };

    sendImageButton.onclick = function (event) {
        let file = fileInput.files[0];
        sendMessage(file);
        fileInput.value = null;
    };

    function sendMessage(message) {
        socket.send(message);
        addMessageToWindow("Sent Message: " + message);
    }

    function addMessageToWindow(message) {
        messageWindow.innerHTML += `<div>${message}</div>`
    }

    function addImageToWindow(image) {
        let url = URL.createObjectURL(new Blob([image]));
        messageWindow.innerHTML += `<img src="${url}"/>`
    }
</script>
</html>

现在,您将需要配置Spark以查找您的index.html并在运行应用程序时初始化服务器。 您还可以定义服务器将在其上侦听连接的端口。

里面的主要的方法应用程式类,在下面添加以下内容webSocket:

staticFileLocation("static");
port(8080)
init();

Start the Application

WebSocket服务器现已完成。 使用启动您的应用程序Gradle运行应用程序目录中的命令。

You can access your application at http://localhost:8080 where you will be greeted with the following page:

Sample JavaScript-enabled client for testing the WebSocket server.

“已连接”消息表明JavaScript客户端能够建立连接。

通过在输入字段中键入并单击发送按钮来尝试发送文本消息。 另外,请尝试上传图片。 在这两种情况下,您都应该看到相同的消息,并且回显了图像。

Sample JavaScript-enabled client showing a text and binary message echoed back.

Conclusion

In this tutorial you learned how to create a WebSocket server using Spark which can receive both binary and text messages. The finished code for this tutorial can be found on the nexmo-community/websocket-spark-framework repository.

Want to implement WebSockets into your existing Spring application? Maybe you want to learn about Creating a w ^ebSocket Server with Spring Boot?

没有框架? 没问题! 请继续阅读下一个教程,在该教程中,我将向您展示如何使用Java API for WebSockets创建WebSocket服务器。

Did you know that you can use WebSocket as an endpoint in a Nexmo Call Control Object? Look at this example on Streaming Calls to a Browser with Voice WebSockets.

Want to see an interesting use of WebSockets? Look at the nexmo-community/dtmf-snake repository to see some code which lets you play a game of snake using dual-tone multi-frequency signals.

from: https://dev.to//vonagedev/creating-a-websocket-server-with-the-spark-framework-1837

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值