抖音弹幕游戏开发之第5集:接收第一条弹幕消息·优雅草云桧·卓伊凡

《抖音弹幕游戏开发专栏》是优雅草建立的专栏,由优雅草资深开发工程师云桂提供实战教学配对发布有对应的视频教程,以下内容为技术文稿,卓伊凡辅助。

抖音弹幕游戏开发之第5集:接收第一条弹幕消息·优雅草云桧·卓伊凡

第5集:接收第一条弹幕消息

添加on_message函数

在现有代码中添加消息接收函数:

def on_message(ws, message):
    print(f"收到消息: {message}")

注册on_message

修改WebSocket创建代码,添加 on_message

ws = websocket.WebSocketApp(
    "ws://localhost:12011",
    on_open=on_open,
    on_message=on_message,  # 添加这一行
    on_close=on_close,
    on_error=on_error
)

注意on_error 后面要加逗号!

完整代码

import websocket

def on_open(ws):
    print("WebSocket连接成功!")

def on_close(ws, close_status_code, close_msg):
    print("WebSocket连接关闭")

def on_error(ws, error):
    print(f"发生错误: {error}")

def on_message(ws, message):
    print(f"收到消息: {message}")

ws = websocket.WebSocketApp(
    "ws://localhost:12011",
    on_open=on_open,
    on_message=on_message,
    on_close=on_close,
    on_error=on_error
)

ws.run_forever()

测试步骤

  1. 启动弹幕工具
  2. 进入一个抖音直播间
  3. 运行程序:python main.py
  4. 观察控制台输出

弹幕数据示例

{
    "uid": "MS4wLjABAAAA...",
    "name": "用户昵称",
    "msgType": "弹幕",
    "content": "这是一条弹幕"
}

不同消息类型

弹幕消息

{"msgType": "弹幕", "content": "666"}

礼物消息

{"msgType": "礼物", "giftName": "玫瑰花", "giftCount": 1}

点赞消息

{"msgType": "点赞", "count": 10}

常见问题

问题解决方法
没有弹幕数据选择人气高的直播间
工具未连接确保显示"已连接"状态
数据显示不完整正常现象,下一集会格式化

本集总结

  • ✅ 添加on_message回调函数
  • ✅ 注册消息接收功能
  • ✅ 成功接收第一条弹幕消息
  • ✅ 观察不同类型的消息数据

下一集:解析JSON数据

0
0
0
0
评论
未登录
暂无评论