Smart_Talker/udp_server.py
2025-04-17 14:21:53 +08:00

68 lines
2.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import socket
import time
def start_server():
# 创建 UDP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('127.0.0.1', 38888))
print("UDP服务器启动监听端口 38888...")
# 记录客户端状态
client_state = {}
while True:
try:
# 接收数据
data, client_address = server_socket.recvfrom(4096)
message = data.decode('utf-8')
print(f"收到来自 {client_address} 的消息: {message}")
# 初始化客户端状态
if client_address not in client_state:
client_state[client_address] = "初始化"
# 处理不同类型的消息
if message == "唤醒连接":
response = "连接成功"
server_socket.sendto(response.encode('utf-8'), client_address)
client_state[client_address] = "等待唤醒"
elif message == "HEARTBEAT":
# 心跳包不需要响应
continue
elif message == "打开助手":
print(f"客户端 {client_address} 检测到唤醒词")
# 这里一定要发送"开始对话"指令
response = "开始对话"
server_socket.sendto(response.encode('utf-8'), client_address)
client_state[client_address] = "录音中"
print(f"已发送指令: {response}")
elif message == "结束对话":
print(f"客户端 {client_address} 结束对话")
# 确保发送开始唤醒指令
response = "开始唤醒"
server_socket.sendto(response.encode('utf-8'), client_address)
client_state[client_address] = "等待唤醒"
print(f"已发送指令: {response}")
elif message.startswith("录音完成:"):
print(f"收到录音文件: {message}")
# 确保发送开始唤醒指令
response = "开始唤醒"
server_socket.sendto(response.encode('utf-8'), client_address)
client_state[client_address] = "等待唤醒"
print(f"已发送指令: {response}")
# 打印当前客户端状态
print(f"客户端 {client_address} 当前状态: {client_state.get(client_address, '未知')}")
except Exception as e:
print(f"发生错误: {e}")
if __name__ == "__main__":
try:
start_server()
except KeyboardInterrupt:
print("\n服务器关闭")