ZBLOG

websocket代码实例

下面是一个简单的 WebSocket 代码示例,展示了如何在客户端使用 JavaScript 创建 WebSocket 连接,并与服务器进行通信。

WebSocket 客户端示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Example</title>
</head>
<body>

<h2>WebSocket Example</h2>
<button id="sendMessage">Send Message</button>
<div id="messages"></div>

<script>
    // 创建 WebSocket 连接
    const wsUrl = "wss://example.com/socket"; // 替换为实际的 WebSocket URL
    const socket = new WebSocket(wsUrl);

    // 当连接打开时触发
    socket.onopen = function(event) {
        console.log("WebSocket is open now.");
        socket.send("Hello Server!"); // 向服务器发送一条消息
    };

    // 接收消息时触发
    socket.onmessage = function(event) {
        console.log("Message from server: ", event.data);
        document.getElementById("messages").innerHTML += "<p>" + event.data + "</p>";
    };

    // 连接关闭时触发
    socket.onclose = function(event) {
        console.log("WebSocket is closed now.");
    };

    // 出现错误时触发
    socket.onerror = function(error) {
        console.error("WebSocket Error: ", error);
    };

    // 按钮点击事件,发送消息到服务器
    document.getElementById("sendMessage").onclick = function() {
        if (socket.readyState === WebSocket.OPEN) { // 确保连接已开启
            socket.send("This is a message from the client!");
        } else {
            console.error("WebSocket is not open. Unable to send message.");
        }
    };
</script>

</body>
</html>

如何运行该示例

  1. 将上述代码保存为 index.html 文件。
  2. 替换 wsUrl 的值为你实际使用的 WebSocket URL(如 ws://localhost:8080 或其他有效地址)。
  3. 在支持 WebSockets 的浏览器中打开该 HTML 文件。
  4. 点击 “Send Message” 按钮,可以向服务器发送消息并查看从服务器接收到的消息。

注意事项

  • 确保你的后端有一个可以接受 WebSocket 连接的服务正在运行。常用的后端技术有 Node.js、Java、Python 等。
  • 如果使用的是本地开发环境,请确保跨域和安全设置都配置正确。


    内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=18778

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?