gpt4 book ai didi

java - 如何将 web-socket 映射到 url 模式?

转载 作者:行者123 更新时间:2023-11-30 06:38:33 24 4
gpt4 key购买 nike

我需要映射网络套接字。在 Servlet 中,我使用注释或 web.xml 进行映射,但如何为服务器套接字创建 url 模式。如果我的 webapp 文件夹中有 index.html,如何确定浏览器的 URL 模式,该模式将与我的页面关联?

我有服务器部分:

@ApplicationScoped
@ServerEndpoint(value = "/index")// May be this mapping but it's don't work.
public class ChatServer {
private static final Logger LOGGER =
Logger.getLogger(ChatServer.class.getName());

@OnOpen
public void onOpen(Session session) {
LOGGER.log(Level.INFO, "New connection with client: {0}",
session.getId());
}

@OnMessage
public String onMessage(String message, Session session) {
LOGGER.log(Level.INFO, "New message from Client [{0}]: {1}",
new Object[] {session.getId(), message});
return "Server received [" + message + "]";
}

@OnClose
public void onClose(Session session) {
LOGGER.log(Level.INFO, "Close connection for client: {0}",
session.getId());
}

@OnError
public void onError(Throwable exception, Session session) {
LOGGER.log(Level.INFO, "Error for client: {0}", session.getId());
}
}

还有我的index.html:

<!DOCTYPE html>
<html>
<head>
<title>JEE7 WebSocket Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
var chatClient = new WebSocket("ws://localhost:8080");

chatClient.onmessage = function(evt) {
var p = document.createElement("p");
p.setAttribute("class", "server");
p.innerHTML = "Server: " + evt.data;
var container = document.getElementById("container");
container.appendChild(p);
};
function send() {
var input = document.getElementById("message");
var p = document.createElement("p");
p.setAttribute("class", "client");
p.innerHTML = "Me: " + input.value;
var container = document.getElementById("container");
container.appendChild(p);
chatClient.send(input.value);
input.value = "";
}
</script>
</head>
<body>
<h1>JEE7 WebSocket Example</h1>
<div id="container">

</div>
<input type="text" id="message" name="message" />
<button type="button" id="send" onclick="send()">Send</button>
</body>
</html>

如何将我的服务器端与 index.html 关联并将我的 html 发送到浏览器?

最佳答案

ws://localhost:8080/ContextPath/index

关于java - 如何将 web-socket 映射到 url 模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44792076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com