admin管理员组文章数量:1122832
I'm working on a Java JEE application using WebSocket with a Tomcat 10.1 server. My goal is to create a one-player (host) game via a WebSocket and allow other players to join this game in real time locally by replacing “localhost” with the host player's ipv4. However, I'm running into a problem: the onMessage method in my WebSocket class never fires, even when I send a message from the client.
Here is my lobby.jsp page which has 2 buttons create and join.
lobby.jsp :
<body> Bienvenue, <%= username %>! Choisissez une option pour continuer :
<form action="createGameSocket" method="POST" style="display:inline;">
<button type="submit" class="button">Create Game</button>
</form>
<button onclick="joinGame(event)" class="button">Join Game</button>
<script>
function joinGame(event) {
event.preventDefault();
window.location.href = "joinGame.jsp";
}
</script>
when I press "create Game" I get this :
CreateGameServlet:
package controller;
import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession;
import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement;
@WebServlet("/createGameSocket") public class CreateGameServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String username = (String) session.getAttribute("username");
if (username == null) {
response.sendRedirect("index.jsp");
return;
}
String gameCode = java.util.UUID.randomUUID().toString().substring(0, 6).toUpperCase();
session.setAttribute("gameCode", gameCode);
System.out.println("Voici le gameCode : " + gameCode);
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/game_db", "root", "test");
String insertQuery = "INSERT INTO games (host_player_id, code, status) VALUES (?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(insertQuery);
int hostPlayerId = 1; // À modifier pour récupérer l'ID réel de l'utilisateur connecté
stmt.setInt(1, hostPlayerId);
stmt.setString(2, gameCode);
stmt.setString(3, "waiting");
stmt.executeUpdate();
stmt.close();
conn.close();
response.sendRedirect("createGame.jsp?code=" + gameCode);
} catch (Exception e) {
e.printStackTrace();
response.getWriter().println("Erreur lors de la création de la partie : " + e.getMessage());
}
}
}
which will call the createGame script:
createGame.jsp
<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<title>Créer une partie</title>
<h1>Partie créée avec succès</h1>
<p>Attendez que les joueurs se connectent, puis démarrez la partie.</p>
<form action="startGame.jsp" method="POST">
<button type="submit" class="button">Démarrer la partie</button>
</form>
<h1>Partie créée avec succès</h1>
<p>Donnez ces informations aux joueurs pour qu'ils se connectent :</p>
<p class="info" >Adresse IPv4 : 192.168.56.1</p>
<p class="info" >Code de la partie : <%= request.getParameter("code") %></p>
<p class="info" >Joueurs connectés : <span id="players"></span></p>
<script>
const gameCode = "<%= request.getParameter("code") %>";
const socket = new WebSocket("ws://192.168.56.1:8080/gameSocket");
socket.onopen = () => {
console.log("Connexion WebSocket ouverte");
socket.send(JSON.stringify({ type: "host", gameCode: gameCode }));
};
socket.onmessage = (event) => {
console.log("Message reçu : ", event.data);
const data = JSON.parse(event.data);
if (data.message) {
document.getElementById("players").textContent = data.message;
}
};
socket.onerror = (error) => {
console.error("Erreur WebSocket : ", error);
};
socket.onclose = () => {
console.log("Connexion WebSocket fermée");
};
function startGame() {
console.log("Partie démarrée !");
}
</script>
just in case : web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns=";
xmlns:xsi=";
xsi:schemaLocation=" .xsd"
version="5.0">
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.jsp</welcome-file>
<welcome-file>default.htm</welcome-file>
</welcome-file-list>
</web-app>
本文标签: Websocket always closed using Tomcat 101 in Java JEEStack Overflow
版权声明:本文标题:Websocket always closed using Tomcat 10.1 in Java JEE - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736284005a1927153.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论