王小虫虫 2022-06-14 22:35 采纳率: 40%
浏览 17

实时收发python socket 客户端

问题遇到的现象和发生背景

我通过递归实现了python socket client 实现,但是在记录日志时,出现太多重复的数据,这是什么原因造成的呢

问题相关代码,请勿粘贴截图
import ast
import json
import socket
import time
import random

from settings.record_log import loggers


class Client:

    def __init__(self, host, port, buffer=1024, timeout=10, encoding='utf-8'):
        """
        初始化
        Args:
            host: 建立连接的IP
            port: 建立连接的端口
            buffer: 一次读取的字节大小
            timeout: 超时时间
            encoding: 字符编码格式
        """
        self.host = host
        self.port = port
        self.buffer = buffer
        self.timeout = timeout
        self.encoding = encoding
        self.tcp_client_socket = None

    def connect(self):
        """
        服务端应用程序建立连接
        Returns:

        """

        # 创建tcp客户端套接字
        # 1. AF_INET:表示ipv4
        # 2. SOCK_STREAM: tcp传输协议
        try:
            self.tcp_client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.tcp_client_socket.connect((self.host, self.port))
        except socket.error as e:
            print(e)
            self.tcp_client_socket.close()
            time.sleep(5)
            self.connect()

    def send_data(self, send_data: json, frame_number):
        """
        发送数据
        Args:
            send_data: 发送数据体,默认为json格式
            frame_number: 推演结束条件

        Returns:
            无
        """
        # 接收数据进行解码
        send_data = send_data.encode(self.encoding)
        logger = loggers("../logs/socket_log.txt")
        # logger.debug("客户端发送的数据:"+ str(send_data))
        if frame_number <= 1000:
            while True:
                self.tcp_client_socket.send(send_data)
                # 接收数据, 这次接收的数据最大字节数是1024
                server_byte_data = self.tcp_client_socket.recv(self.buffer)
                # 对数据进行解码
                try:
                    server_decode_data = ast.literal_eval(server_byte_data.decode(self.encoding))
                    #print("接收服务端的数据为:", server_decode_data, type(server_decode_data))
                    logger.info("接收服务端的数据为:"+str(server_decode_data)+str(type(server_decode_data)))
                except Exception as e:
                    server_decode_data = server_byte_data.decode(self.encoding)
                    # print("接收异常-服务端数据为:", server_decode_data, type(server_decode_data))
                    logger.error("接收异常-服务端数据为:"+str(server_decode_data)+ str(type(server_decode_data)))

                if isinstance(server_decode_data, dict):
                    action_type = server_decode_data.get('action_type')
                    if action_type == "move":
                        server_decode_data['data']['destination']['X'] = random.randint(0, 200)
                        server_decode_data['data']['destination']['Z'] = random.randint(0, 200)
                        self.send_data(self.dict_to_decode(server_decode_data), frame_number)

                    if action_type == "fire":
                        # 该数据结构未知
                        pass

                    if action_type == "observation":
                        pass

        self.close_client()

    def close_client(self):
        """
        关闭套接字
        Returns:

        """
        self.tcp_client_socket.close()

    def dict_to_decode(self, data):
        """
        python字典转字节格式
        Args:
            data: 传入python字典
            
        Returns:
            返回字节格式数据
        """
        data = bytes('{}'.format(data), 'utf-8')
        data = data.decode(self.encoding)
        return data


if __name__ == '__main__':
    c1 = Client('127.0.0.1', 6321)
    c1.connect()
    data = {
        "action_type": "move",
        "room_id": 1,
        "camp_id": 0,
        "data": {
            "obj_id": 102,
            "type": 1,
            "destination": {"X": random.randint(1, 100), "Y": random.randint(1, 100), "Z": random.randint(1, 100)}
        }
    }
    # 字典转字节
    byte_data = c1.dict_to_decode(data)

    c1.send_data(byte_data, 999)




运行结果及报错内容

[2022-06-14 22:32:53] [INFO] 接收服务端的数据为:{'action_type': 'move', 'room_id': 1, 'camp_id': 0, 'data': {'obj_id': 102, 'type': 1, 'destination': {'X': 58, 'Y': 42, 'Z': 23}}}<class 'dict'>
[2022-06-14 22:32:54] [INFO] 接收服务端的数据为:{'action_type': 'move', 'room_id': 1, 'camp_id': 0, 'data': {'obj_id': 102, 'type': 1, 'destination': {'X': 179, 'Y': 42, 'Z': 198}}}<class 'dict'>
[2022-06-14 22:32:54] [INFO] 接收服务端的数据为:{'action_type': 'move', 'room_id': 1, 'camp_id': 0, 'data': {'obj_id': 102, 'type': 1, 'destination': {'X': 179, 'Y': 42, 'Z': 198}}}<class 'dict'>
[2022-06-14 22:32:55] [INFO] 接收服务端的数据为:{'action_type': 'move', 'room_id': 1, 'camp_id': 0, 'data': {'obj_id': 102, 'type': 1, 'destination': {'X': 41, 'Y': 42, 'Z': 130}}}<class 'dict'>
[2022-06-14 22:32:55] [INFO] 接收服务端的数据为:{'action_type': 'move', 'room_id': 1, 'camp_id': 0, 'data': {'obj_id': 102, 'type': 1, 'destination': {'X': 41, 'Y': 42, 'Z': 130}}}<class 'dict'>
[2022-06-14 22:32:55] [INFO] 接收服务端的数据为:{'action_type': 'move', 'room_id': 1, 'camp_id': 0, 'data': {'obj_id': 102, 'type': 1, 'destination': {'X': 41, 'Y': 42, 'Z': 130}}}<class 'dict'>
[2022-06-14 22:32:56] [INFO] 接收服务端的数据为:{'action_type': 'move', 'room_id': 1, 'camp_id': 0, 'data': {'obj_id': 102, 'type': 1, 'destination': {'X': 14, 'Y': 42, 'Z': 66}}}<class 'dict'>
[2022-06-14 22:32:56] [INFO] 接收服务端的数据为:{'action_type': 'move', 'room_id': 1, 'camp_id': 0, 'data': {'obj_id': 102, 'type': 1, 'destination': {'X': 14, 'Y': 42, 'Z': 66}}}<class 'dict'>
[2022-06-14 22:32:56] [INFO] 接收服务端的数据为:{'action_type': 'move', 'room_id': 1, 'camp_id': 0, 'data': {'obj_id': 102, 'type': 1, 'destination': {'X': 14, 'Y': 42, 'Z': 66}}}<class 'dict'>
[2022-06-14 22:32:56] [INFO] 接收服务端的数据为:{'action_type': 'move', 'room_id': 1, 'camp_id': 0, 'data': {'obj_id': 102, 'type': 1, 'destination': {'X': 14, 'Y': 42, 'Z': 66}}}<class 'dict'>
[2022-06-14 22:32:57] [INFO] 接收服务端的数据为:{'action_type': 'move', 'room_id': 1, 'camp_id': 0, 'data': {'obj_id': 102, 'type': 1, 'destination': {'X': 195, 'Y': 42, 'Z': 199}}}<class 'dict'>
[2022-06-14 22:32:57] [INFO] 接收服务端的数据为:{'action_type': 'move', 'room_id': 1, 'camp_id': 0, 'data': {'obj_id': 102, 'type': 1, 'destination': {'X': 195, 'Y': 42, 'Z': 199}}}<class 'dict'>
[2022-06-14 22:32:57] [INFO] 接收服务端的数据为:{'action_type': 'move', 'room_id': 1, 'camp_id': 0, 'data': {'obj_id': 102, 'type': 1, 'destination': {'X': 195, 'Y': 42, 'Z': 199}}}<class 'dict'>
[2022-06-14 22:32:57] [INFO] 接收服务端的数据为:{'action_type': 'move', 'room_id': 1, 'camp_id': 0, 'data': {'obj_id': 102, 'type': 1, 'destination': {'X': 195, 'Y': 42, 'Z': 199}}}<class 'dict'>
[2022-06-14 22:32:57] [INFO] 接收服务端的数据为:{'action_type': 'move', 'room_id': 1, 'camp_id': 0, 'data': {'obj_id': 102, 'type': 1, 'destination': {'X': 195, 'Y': 42, 'Z': 199}}}<class 'dict'>
[2022-06-14 22:32:58] [INFO] 接收服务端的数据为:{'action_type': 'move', 'room_id': 1, 'camp_id': 0, 'data': {'obj_id': 102, 'type': 1, 'destination': {'X': 85, 'Y': 42, 'Z': 187}}}<class 'dict'>
[2022-06-14 22:32:58] [INFO] 接收服务端的数据为:{'action_type': 'move', 'room_id': 1, 'camp_id': 0, 'data': {'obj_id': 102, 'type': 1, 'destination': {'X': 85, 'Y': 42, 'Z': 187}}}<class 'dict'>
[2022-06-14 22:32:58] [INFO] 接收服务端的数据为:{'action_type': 'move', 'room_id': 1, 'camp_id': 0, 'data': {'obj_id': 102, 'type': 1, 'destination': {'X': 85, 'Y': 42, 'Z': 187}}}<class 'dict'>
[2022-06-14 22:32:58] [INFO] 接收服务端的数据为:{'action_type': 'move', 'room_id': 1, 'camp_id': 0, 'data': {'obj_id': 102, 'type': 1, 'destination': {'X': 85, 'Y': 42, 'Z': 187}}}<class 'dict'>
[2022-06-14 22:32:58] [INFO] 接收服务端的数据为:{'action_type': 'move', 'room_id': 1, 'camp_id': 0, 'data': {'obj_id': 102, 'type': 1, 'destination': {'X': 85, 'Y': 42, 'Z': 187}}}<class 'dict'>
[2022-06-14 22:32:58] [INFO] 接收服务端的数据为:{'action_type': 'move', 'room_id': 1, 'camp_id': 0, 'data': {'obj_id': 102, 'type': 1, 'destination': {'X': 85, 'Y': 42, 'Z': 187}}}<class 'dict'>

Process finished with exit code -1

我的解答思路和尝试过的方法

我不知道为什么会重复打印这么多次重复的相同时间的日志,这个该如何解决

我想要达到的结果

我想实现客户端 实时接收服务端发送过来的数据 , 处理后 再发送给服务端

  • 写回答

1条回答 默认 最新

  • zpeien Android领域新星创作者 2022-06-15 15:03
    关注

    写日志的循环都没有跳出条件,肯定会一直重复输出相同的日志啊,你把这个循环给他一个退出的条件就行了。

    img

    评论

报告相同问题?

问题事件

  • 创建了问题 6月14日

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错