WebSocket学习笔记

WebSocket学习笔记

1:WebSocket的客户端(浏览器)实现

1.1:WebSocket对象

实现WebSocket的Web浏览器通过WebSocket对象公开所有必须的客户端功能(主要支持HTML5的浏览器)。一下API用于创建WebSocket对象:

var ws = new WebSocket(url)

参数url格式说明:ws:// ip地址 : 端口号 / 资源名称

1.2:WebSocket事件

WebSocket对象的相关事件

事件事件处理程序描述
openwebsocket对象.onopen连接建立时触发
messagewebsocket对象.onmessage客户端接收服务端数据时触发
errorwebsocket对象.onerror通信发生错误时触发
closewebsocket对象.onclose连接关闭时触发
1.3:WebSocket方法

WebSocket对象的相关方法

方法描述
send()试用连接发送数据

2:WebSocket的服务端Python实现

接收到数据发送一个I got your message: (接收到的数据)

然后开始不停发送时间数据

import asyncio
import websockets
import time


async def echo(websocket, path):
    async for message in websocket:
        message = "I got your message: {}".format(message)
        await websocket.send(message)

        while True:
            t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            await websocket.send(t)


asyncio.get_event_loop().run_until_complete(websockets.serve(echo, 'localhost', 50500))
asyncio.get_event_loop().run_forever()

3:WebSoket的客户端Vue实现

<template>
    <div>
        <button @click="send">发送消息</button>
        <input v-model="receivedMessage"/>
    </div>
</template>

<script>
export default {
    data () {
        return {
            path:"ws://localhost:50500",
            socket:"",
            Send_txt:"ok",
            receivedMessage:""
        }
    },
    mounted () {
        // 初始化
        this.WebSocket_init()
        console.log("sasasa")
        this.send
    },
    methods: {
        WebSocket_init() {
            if(typeof(WebSocket) === "undefined"){
                alert("您的浏览器不支持WebSocket!")
            }else{
                // 建立连接
                this.socket = new WebSocket(this.path)
                // 连接成功是调用open函数
                this.socket.onopen = this.open
                // 出错时调用errer函数
                this.socket.onerror = this.error
                // 接收到消息时调用getMessage函数
                this.socket.onmessage = this.getMessage
            }
        },
        open() {
            console.log("WebSocket连接成功")
        },
        error() {
            console.log("WebSocket错误")
        },
        // 接收到服务端数据
        getMessage(msg) {
            console.log(msg)
            // 转String数据为Json
        	var testJson = eval("(" + msg.data + ")");
            this.receivedMessage = testJson.tag
            console.log(testJson.data[0].id)
        },
        send() {
            this.socket.send(this.Send_txt)
        },
        close() {
            console.log("WebSocket已关闭")
        }
    },
    destroyed () {
        this.socket.onclose = this.close
    }
}
</script>

<style>

</style>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Addam Holmes

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值