IntelliJIDEA 测试websocket
时间: 2023-07-04 12:20:19 浏览: 228
在 IntelliJ IDEA 中测试 WebSocket,可以按照以下步骤操作:
1. 引入 WebSocket 的依赖项,可以参考上一条回答中的第一步操作。
2. 创建 WebSocket 服务端代码:
```
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
@ServerEndpoint("/myendpoint")
public class MyServerEndpoint {
@OnOpen
public void onOpen(Session session) {
System.out.println("Connected to endpoint: " + session.getId());
}
@OnMessage
public void onMessage(String message, Session session) throws IOException, InterruptedException {
System.out.println("Received message: " + message);
session.getBasicRemote().sendText("Server received message: " + message);
}
@OnError
public void onError(Throwable t) {
t.printStackTrace();
}
}
```
3. 创建前端 HTML 页面,用于连接 WebSocket 服务器并发送消息:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WebSocket Test</title>
<script type="text/javascript">
var webSocket = new WebSocket("ws://localhost:8080/myapp/myendpoint");
webSocket.onopen = function(event) {
console.log("Connected to WebSocket server.");
};
webSocket.onmessage = function(event) {
console.log("Received message: " + event.data);
};
function sendMessage() {
var message = document.getElementById("message").value;
webSocket.send(message);
console.log("Sent message: " + message);
}
</script>
</head>
<body>
<input type="text" id="message">
<button onclick="sendMessage()">Send</button>
</body>
</html>
```
4. 运行 WebSocket 服务器代码并启动前端 HTML 页面,即可连接到 WebSocket 服务器并发送消息。
希望以上回答能够帮助到你!
阅读全文