Home  >  Article  >  Java  >  How does Java Websocket implement online gaming functions?

How does Java Websocket implement online gaming functions?

王林
王林Original
2023-12-02 14:44:381580browse

Java Websocket如何实现在线游戏功能?

Java Websocket is a full-duplex communication protocol based on the TCP protocol, which can achieve two-way communication on a persistent connection. This makes Java Websocket very suitable for the development of real-time online games, because games require fast interaction and real-time communication.

In this article, we will introduce how to use Java Websocket to implement online gaming functions. We will use Java 8 and Tomcat 8 as the development environment, and the front-end page uses HTML5 and JavaScript.

  1. Establishing a WebSocket connection

First, we need to create a WebSocket connection. We can achieve this functionality by writing a WebSocket endpoint. In a JavaWeb application, we can configure the Websocket endpoint using javax.websocket.Endpoint.

The following is the implementation of the Websocket endpoint:

@ServerEndpoint("/game")
public class GameEndpoint {

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("WebSocket Opened: " + session.getId());
        GameSessionManager.getInstance().addSession(session); // 将Session加入管理器
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("WebSocket Message received: " + message);
        GameSessionManager.getInstance().handleMessage(message, session); // 处理消息
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("WebSocket Closed: " + session.getId());
        GameSessionManager.getInstance().removeSession(session); // 将Session从管理器中移除
    }

    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }
}

In this endpoint, we define four annotations:

  • @ServerEndpoint("/game") definition The path to this endpoint is "/game".
  • @OnOpen defines what this endpoint does when WebSocket is opened, such as adding a WebSocket connection to the manager.
  • @OnMessage defines what this endpoint does when WebSocket receives a message, such as sending the message to all connected WebSocket clients.
  • @OnClose defines what this endpoint does when WebSocket is closed, such as removing the WebSocket connection from the manager.
  • @OnError defines what this endpoint does when a WebSocket error occurs.

Note: This is just a simple example, more error handling and security checks should be performed in actual applications.

  1. Manage game sessions

We need to create a GameSessionManager class to manage game sessions. GameSessionManager is a singleton class used to manage all WebSocket connections and handle game-related messages.

The following is the implementation of GameSessionManager:

public class GameSessionManager {

    private Set<Session> sessions = new HashSet<>();
    private static GameSessionManager instance;

    private GameSessionManager() {
    }

    public static GameSessionManager getInstance() {
        if (instance == null) {
            synchronized (GameSessionManager.class) {
                if (instance == null) {
                    instance = new GameSessionManager();
                }
            }
        }
        return instance;
    }

    public void addSession(Session session) {
        sessions.add(session);
    }

    public void removeSession(Session session) {
        sessions.remove(session);
    }

    public void handleMessage(String message, Session session) {
        // TODO 处理消息
    }

    public void broadcast(String message) {
        for (Session session : sessions) {
            send(message, session);
        }
    }

    public void send(String message, Session session) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this class, we create a Session collection to store all WebSocket sessions. Use the getInstance() method to obtain the singleton object of GameSessionManager. When adding and removing WebSocket connections, we simply add or remove the connection to the collection. When broadcasting a message, we loop through all WebSocket sessions and send the message to each one. When sending a message, we use the session.getBasicRemote() method to get the basic remote port, and then call the sendText() method to send the message to the client.

  1. Handling game messages

We will handle the game messages from the client in the GameSessionManager class and send them back to the client. We'll also deal with game logic here.

Here is a simple "chat" game with "hello" and "bye" operations as an example:

public void handleMessage(String message, Session session) {
    JSONObject json = new JSONObject(message);
    String action = json.getString("action");
    switch (action) {
        case "hello":
            String name = json.optString("name");
            broadcast(name + " joined the game.");
            break;
        case "bye":
            String playerName = json.optString("name");
            broadcast(playerName + " left the game.");
            break;
        default:
            System.out.println("Unknown action: " + action);
            break;
    }
}

In this implementation, we first parse the received message as JSON format. We then check the "Action" field of the message and perform the appropriate action based on the different operations. If the action is "hello", we get the player's name from the message and use the broadcast method to send the welcome message to all players. If the operation is "bye", we also get the player's name from the message and use the broadcast method to send the farewell message to all players. Otherwise, we print a message for unknown operation.

  1. Build a front-end page

The front-end page is implemented using HTML5 and JavaScript. We need to write a JavaScript class that implements WebSocket. In a JavaWeb application, we can use JavaScript's WebSocket object to create a WebSocket connection.

The following is the JavaScript class that implements WebSocket:

var webSocket = null;
var url = "ws://" + window.location.hostname + ":" + window.location.port + "/game";

function connectWebSocket() {
    if("WebSocket" in window) {
        webSocket = new WebSocket(url);

        webSocket.onopen = function(event) {
            console.log("WebSocket opened.");
        };

        webSocket.onmessage = function(event) {
            console.log("WebSocket message received: " + event.data);
            handleMessage(event.data);
        };

        webSocket.onclose = function(event) {
            console.log("WebSocket closed.");
        };
    } else {
        console.log("WebSocket is not supported by this browser.");
    }
}

function sendMessage(message) {
    if(webSocket) {
        webSocket.send(message);
    } else {
        console.log("WebSocket is not connected.");
    }
}

In this implementation, we first check whether WebSocket is supported. If so, we will create a WebSocket object using WebSocket's constructor and assign it to the webSocket variable. We have defined three WebSocket event handlers:

  • websocket.onopen The operations performed when the WebSocket is opened, such as initiating a connection request to the server.
  • websocket.onmessage defines the operations performed by WebSocket when it receives a message, such as calling the handleMessage function to process the message.
  • websocket.onclose defines what to do when WebSocket is closed, such as trying to reconnect.

We also define a sendMessage function, which uses the send method of the WebSocket object to send the message to the server.

  1. Implement front-end interaction

We will use jQuery to implement front-end interaction and send game messages to the server.

The following is the implementation of the handleMessage function:

function handleMessage(message) {
    var json = $.parseJSON(message);
    var action = json.action;
    switch (action) {
        case "hello":
            var name = json.name;
            console.log("Player " + name + " joined the game.");
            break;
        case "bye":
            var playerName = json.name;
            console.log("Player " + playerName + " left the game.");
            break;
        default:
            console.log("Unknown action: " + action);
            break;
    }
}

$(document).ready(function() {
    connectWebSocket();

    $("#btnHello").click(function(event) {
        var playerName = $("#txtName").val();
        var message = '{"action": "hello", "name": "' + playerName + '"}';
        sendMessage(message);
    });

    $("#btnBye").click(function(event) {
        var playerName = $("#txtName").val();
        var message = '{"action": "bye", "name": "' + playerName + '"}';
        sendMessage(message);
    });
});

In this implementation, we use jQuery's $.parseJSON function to parse the received message into JSON format. We then check the "Action" field of the message and perform the appropriate action based on the different operations. If the action is "hello", we get the player's name from the message and print the message to join the game. If the action is "bye", we also get the player's name from the message and print the message leaving the game. Otherwise, we print a message for unknown operation.

我们还将为两个按钮分别定义单击事件,这些事件将生成相应的JSON消息并使用'use SendMessage()函数向服务器发送消息。

  1. 测试

现在我们已经完成了Java Websocket实现在线游戏的所有工作。我们需要在Tomcat服务器上启动我们的应用程序并在浏览器中打开前端页面。我们可以使用多个浏览器测试在线游戏的功能。

下面是完整的游戏前端代码,供您参考:

<!doctype html>
<html>
<head>
    <title>WebSocket Chat</title>
    <meta charset="utf-8"/>
    <script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
    <script src="websockets.js"></script>
    <script>
        $(document).ready(function() {
            connectWebSocket();

            $("#btnHello").click(function(event) {
                var playerName = $("#txtName").val();
                var message = '{"action": "hello", "name": "' + playerName + '"}';
                sendMessage(message);
            });

            $("#btnBye").click(function(event) {
                var playerName = $("#txtName").val();
                var message = '{"action": "bye", "name": "' + playerName + '"}';
                sendMessage(message);
            });
        });

        function handleMessage(message) {
            var json = $.parseJSON(message);
            var action = json.action;
            switch (action) {
                case "hello":
                    var name = json.name;
                    console.log("Player " + name + " joined the game.");
                    break;
                case "bye":
                    var playerName = json.name;
                    console.log("Player " + playerName + " left the game.");
                    break;
                default:
                    console.log("Unknown action: " + action);
                    break;
            }
        }
    </script>
</head>
<body>
    <div>
        <label>Player name:</label>
        <input type="text" id="txtName"/>
        <button id="btnHello">Join game</button>
        <button id="btnBye">Leave game</button>
    </div>
</body>
</html>

结论

这篇文章主要介绍了使用Java Websocket实现在线游戏的过程。我们在Java 8和Tomcat 8中开发了一个简单的“chat”游戏,并使用HTML5和JavaScript实现了前端。我们展示了如何使用WebSocket端点,如何管理游戏会话,如何处理游戏消息,如何与前端进行交互,并提供了完整的代码示例。

The above is the detailed content of How does Java Websocket implement online gaming functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn