写一个webstock通信的简单案例
时间: 2024-05-08 17:15:49 浏览: 218
这是一个简单的 WebSocket 通信案例:
1. HTML 页面
```html
<!DOCTYPE html>
<html>
<head>
<title>WebSocket 通信</title>
</head>
<body>
<h1>WebSocket 通信</h1>
<form>
<input id="message" type="text" placeholder="输入消息">
<button type="button" onclick="sendMessage()">发送</button>
</form>
<ul id="messages"></ul>
<script>
var socket = new WebSocket("ws://localhost:8080/chat");
socket.onopen = function(event) {
console.log("WebSocket connected!");
}
socket.onmessage = function(event) {
console.log("Received message: " + event.data);
var messageList = document.getElementById("messages");
var messageItem = document.createElement("li");
messageItem.innerText = event.data;
messageList.appendChild(messageItem);
}
function sendMessage() {
var messageInput = document.getElementById("message");
var message = messageInput.value;
socket.send(message);
messageInput.value = "";
}
</script>
</body>
</html>
```
2. Java 后端
```java
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
@ServerEndpoint("/chat")
public class ChatEndpoint {
@OnOpen
public void onOpen(Session session) {
System.out.println("WebSocket opened: " + session.getId());
}
@OnMessage
public void onMessage(Session session, String message) throws IOException {
System.out.println("Received message: " + message);
session.getBasicRemote().sendText(message);
}
@OnClose
public void onClose(Session session) {
System.out.println("WebSocket closed: " + session.getId());
}
@OnError
public void onError(Session session, Throwable throwable) {
System.out.println("WebSocket error: " + throwable.getMessage());
}
}
```
这个案例中,前端页面通过 WebSocket 连接到后端的 `/chat` 端点,当用户输入消息并点击发送按钮时,前端页面会将消息发送给后端并清空输入框。后端收到消息后会将消息发送给所有连接到 `/chat` 端点的客户端。客户端收到消息后会在页面上显示。
阅读全文