html websocket client
时间: 2023-10-18 09:23:40 浏览: 91
As an AI language model, I do not have the ability to create a websocket client in HTML. However, I can give you an idea of how to create a websocket client in HTML.
To create a websocket client in HTML, you need to:
1. Create a new WebSocket object by specifying the URL of the websocket server.
```javascript
var socket = new WebSocket("ws://localhost:8080");
```
2. Add an event listener to the WebSocket object to handle incoming messages.
```javascript
socket.addEventListener("message", function(event) {
console.log("Message received:", event.data);
});
```
3. Send messages to the websocket server using the send() method of the WebSocket object.
```javascript
socket.send("Hello, server!");
```
4. Close the websocket connection when you're done.
```javascript
socket.close();
```
Here is an example HTML code that demonstrates how to create a websocket client:
```html
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Client</title>
</head>
<body>
<h1>WebSocket Client</h1>
<script>
var socket = new WebSocket("ws://localhost:8080");
socket.addEventListener("open", function(event) {
console.log("WebSocket connection opened.");
});
socket.addEventListener("message", function(event) {
console.log("Message received:", event.data);
});
socket.addEventListener("close", function(event) {
console.log("WebSocket connection closed.");
});
socket.send("Hello, server!");
socket.close();
</script>
</body>
</html>
```
阅读全文