美文网首页
使用WebSockets和Spark创建实时聊天应用程序

使用WebSockets和Spark创建实时聊天应用程序

作者: 林海小盆友 | 来源:发表于2019-06-04 13:21 被阅读0次

你将学到什么

在本教程中,我们将创建一个简单的实时聊天应用程序。它将包含一个聊天面板,用于存储您加入后收到的消息,当前连接的用户列表以及用于发送消息的输入字段。我们将使用WebSockets,因为WebSockets通过单个TCP连接为我们提供全双工通信通道,这意味着我们不必另外发送HTTP请求来发送和接收消息。WebSocket连接保持打开状态,大大减少了延迟(和复杂性)。

创建Spark Maven项目

首先,我们需要创建一个Spark Maven项目

<project>
   <!-- model version - always 4.0.0 for Maven 2.x POMs -->
   <modelVersion>4.0.0</modelVersion>

   <!-- project coordinates - values which uniquely identify this project -->
   <groupId>com.mycompany.app</groupId>
   <artifactId>my-app</artifactId>
   <version>1.0</version>
   
   <properties>
       <maven.compiler.source>1.8</maven.compiler.source>
       <maven.compiler.target>1.8</maven.compiler.target>
   </properties>

   <!-- library dependencies -->
   <dependencies>
       <dependency>
           <groupId>com.sparkjava</groupId>
           <artifactId>spark-core</artifactId>
           <version>2.5</version>
       </dependency>
   </dependencies>
</project>

依赖

除了Spark之外,我们将使用简单的Java HTML Builder (j2html)来生成聊天消息。我们的POM.xml应该具有以下依赖项:

<dependencies>
    <dependency>
        <groupId>com.sparkjava</groupId>
        <artifactId>spark-core</artifactId>
        <version>2.5.5</version>
    </dependency>
    <dependency>
        <groupId>com.j2html</groupId>
        <artifactId>j2html</artifactId>
        <version>1.2.0</version>
    </dependency>
     <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20160810</version>
    </dependency>
</dependencies>

创建Java应用程序

我们需要跟踪所有用户并为其分配用户名。我们创建一个映射会话(userUsernameMap),将会话映射到用户名,Spark服务器代码:

public class Chat {
    
    // this map is shared between sessions and threads, so it needs to be thread-safe (http://stackoverflow.com/a/2688817)
    static Map<Session, String> userUsernameMap = new ConcurrentHashMap<>();
    static int nextUserNumber = 1; //Used for creating the next username

    public static void main(String[] args) {
        staticFileLocation("/public"); //index.html is served at localhost:4567 (default port)
        webSocket("/chat", ChatWebSocketHandler.class);
        init();
    }
}

我们还需要创建一些方法来向所有连接的用户发送消息。我们只会向会话状态为open(Session :: isOpen)的用户发送消息。我们使用流和过滤器来减少列表(userUsernameMap的keySet),然后发出一个包含HTML消息和用户名列表(我们的userUsernameMap的值)的JSON结构:

//Sends a message from one user to all users, along with a list of current usernames
public static void broadcastMessage(String sender, String message) {
    userUsernameMap.keySet().stream().filter(Session::isOpen).forEach(session -> {
        try {
            session.getRemote().sendString(String.valueOf(new JSONObject()
                .put("userMessage", createHtmlMessageFromSender(sender, message))
                .put("userlist", userUsernameMap.values())
            ));
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
}

要创建HTML,我们将使用(j2html)。我们将创建一个包含发件人姓名,邮件本身和时间戳的文章标签:

//Builds a HTML element with a sender-name, a message, and a timestamp,
private static String createHtmlMessageFromSender(String sender, String message) {
    return article().with(
            b(sender + " says:"),
            p(message),
            span().withClass("timestamp").withText(new SimpleDateFormat("HH:mm:ss").format(new Date()))
    ).render();
}

设置我们的WebSocketHandler

我们将使用的方法非常简单:在用户连接时将用户添加到userUsernameMap,在断开连接时将其删除,并将所有消息发送给所有用户。由于我们需要用户名,但不想要复杂性,我们将根据有人连接到服务器的时间生成用户名:

@WebSocket
public class ChatWebSocketHandler {
    private String sender, msg;

    @OnWebSocketConnect
    public void onConnect(Session user) throws Exception {
        String username = "User" + Chat.nextUserNumber++;
        Chat.userUsernameMap.put(user, username);
        Chat.broadcastMessage(sender = "Server", msg = (username + " joined the chat"));
    }

    @OnWebSocketClose
    public void onClose(Session user, int statusCode, String reason) {
        String username = Chat.userUsernameMap.get(user);
        Chat.userUsernameMap.remove(user);
        Chat.broadcastMessage(sender = "Server", msg = (username + " left the chat"));
    }

    @OnWebSocketMessage
    public void onMessage(Session user, String message) {
        Chat.broadcastMessage(sender = Chat.userUsernameMap.get(user), msg = message);
    }
}

构建JavaScript客户端

为了使用演示我们的应用程序工作,我们可以构建一个JavaScript客户端。首先我们创建index.html:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>WebsSockets</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div id="chatControls">
        <input id="message" placeholder="Type your message">
        <button id="send">Send</button>
    </div>
    <ul id="userlist"> <!-- Built by JS --> </ul>
    <div id="chat">    <!-- Built by JS --> </div>
    <script src="websocketDemo.js"></script>
</body>
</html>

如您所见,我们引用了一个名为style.css的样式表,它可以在GitHub找到

完成聊天应用程序所需的最后一步是创建websocketDemo.js:

//Establish the WebSocket connection and set up event handlers
var webSocket = new WebSocket("ws://" + location.hostname + ":" + location.port + "/chat/");
webSocket.onmessage = function (msg) { updateChat(msg); };
webSocket.onclose = function () { alert("WebSocket connection closed") };

//Send message if "Send" is clicked
id("send").addEventListener("click", function () {
    sendMessage(id("message").value);
});

//Send message if enter is pressed in the input field
id("message").addEventListener("keypress", function (e) {
    if (e.keyCode === 13) { sendMessage(e.target.value); }
});

//Send a message if it's not empty, then clear the input field
function sendMessage(message) {
    if (message !== "") {
        webSocket.send(message);
        id("message").value = "";
    }
}

//Update the chat-panel, and the list of connected users
function updateChat(msg) {
    var data = JSON.parse(msg.data);
    insert("chat", data.userMessage);
    id("userlist").innerHTML = "";
    data.userlist.forEach(function (user) {
        insert("userlist", "<li>" + user + "</li>");
    });
}

//Helper function for inserting HTML as the first child of an element
function insert(targetId, message) {
    id(targetId).insertAdjacentHTML("afterbegin", message);
}

//Helper function for selecting element by id
function id(id) {
    return document.getElementById(id);
}

现在我们可以尝试在几个不同的浏览器窗口中打开localhost:4567并与自己交谈。

相关文章

网友评论

      本文标题:使用WebSockets和Spark创建实时聊天应用程序

      本文链接:https://www.haomeiwen.com/subject/dqplxctx.html