python unity通讯数据解析

文章描述了一个使用Python编写的基本服务器,通过ZMQ实现客户端请求与服务端响应,以及一个使用C#的Unity客户端发送Hello消息并接收回复的过程,涉及字节编码、浮点数转换和正则表达式处理。
摘要由CSDN通过智能技术生成

python

#
#   Hello World server in Python
#   Binds REP socket to tcp://*:5555
#   Expects b"Hello" from client, replies with b"World"
#

# def strint_to_bytes(string, integer):
#     return string.encode('utf-8') + b'\n' + str(integer).encode('utf-8')

import time
import zmq
import struct
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:5555")

print("Server started")

while True:

    #  Wait for next request from client
    message = socket.recv()
    print("Received request: %s" % message)

    #  Do some 'work'.
    #  Try reducing sleep time to 0.01 to see how blazingly fast it communicates
    #  In the real world usage, you just need to replace time.sleep() with
    #  whatever work you want python to do, maybe a machine learning task?
    time.sleep(1)

    #  Send reply back to client
    #  In the real world usage, after you finish your work, send your output here
    distance = 10.125
    dis_int = 10
    strs = "Elegance is the only beauty that never fades."
    dis = "the distance is %.3f meters. " % distance
    byte_value = dis_int.to_bytes(4, byteorder='little')
    # socket.send(byte_value)

    # 将float转化为bytes
    float_number = 3.1425

    bytes_value = struct.pack("d", float_number) # Big-endian format
    # socket.send(bytes_value)

    # socket.send(dis.encode('utf-8'))
    # socket.send(strs.encode('utf-8'))
    socket.send(dis.encode('utf-8') + b'\n' + strs.encode('utf-8'))

HelloRequester.cs

using AsyncIO;
using NetMQ;
using NetMQ.Sockets;
using System;
using UnityEngine;
using System.Text.RegularExpressions;

/// <summary>
///     Example of requester who only sends Hello. Very nice guy.
///     You can copy this class and modify Run() to suits your needs.
///     To use this class, you just instantiate, call Start() when you want to start and Stop() when you want to stop.
/// </summary>
public class HelloRequester : RunAbleThread
{
    /// <summary>
    ///     Request Hello message to server and receive message back. Do it 10 times.
    ///     Stop requesting when Running=false.
    /// </summary>
    public static string message = null;
    
    protected override void Run()
    {
        ForceDotNet.Force(); // this line is needed to prevent unity freeze after one use, not sure why yet
        using (RequestSocket client = new RequestSocket())
        {
            client.Connect("tcp://localhost:5555");
            string message = null;

            for (int i = 0;  Running; i++)
            {
                Debug.Log("Sending Hello");
                client.SendFrame("Hello");
                // ReceiveFrameString() blocks the thread until you receive the string, but TryReceiveFrameString()
                // do not block the thread, you can try commenting one and see what the other does, try to reason why
                // unity freezes when you use ReceiveFrameString() and play and stop the scene without running the server
                //                string message = client.ReceiveFrameString();
                //                Debug.Log("Received: " + message);
                bool gotMessage = false;
 
                while (Running)
                {
                    gotMessage = client.TryReceiveFrameString(out message); // this returns true if it's successful

                    if (gotMessage) break;
                }

                if (gotMessage)
                {
                    Debug.Log("Received " + message);

                    //Debug.Log("Received " + message[4]);

                    string pattern = @"\d+.\d+";
                    
                    MatchCollection matches = Regex.Matches(message, pattern);

                    foreach (Match match in matches)
                    {
                        //Console.WriteLine(match.Value);
                        Debug.Log(match.Value);
                    }
         

                }
            }
        }

        NetMQConfig.Cleanup(); // this line is needed to prevent unity freeze after one use, not sure why yet
    }

    //protected override void Run()
    //{
    //    ForceDotNet.Force(); // this line is needed to prevent unity freeze after one use, not sure why yet
    //    using (RequestSocket client = new RequestSocket())
    //    {
    //        client.Connect("tcp://localhost:5555");

    //        for (int i = 0; i < 10 && Running; i++)
    //        {
    //            Debug.Log("Sending Hello");
    //            client.SendFrame("Hello");
    //            // ReceiveFrameString() blocks the thread until you receive the string, but TryReceiveFrameString()
    //            // do not block the thread, you can try commenting one and see what the other does, try to reason why
    //            // unity freezes when you use ReceiveFrameString() and play and stop the scene without running the server
    //            //                string message = client.ReceiveFrameString();
    //            //                Debug.Log("Received: " + message);
    //            string message = null;
    //            bool gotMessage = false;

    //            while (Running)
    //            {
    //                gotMessage = client.TryReceiveFrameString(out message); // this returns true if it's successful
    //                if (gotMessage) break;
    //            }

    //            if (gotMessage) Debug.Log("Received " + message);
    //        }
    //    }

    //    NetMQConfig.Cleanup(); // this line is needed to prevent unity freeze after one use, not sure why yet
    //}

}

运行结果

如果是整数

python

    dis_int = 10
    byte_value = dis_int.to_bytes(4, byteorder='little')
    socket.send(byte_value)

unity HelloRequester.cs

using AsyncIO;
using NetMQ;
using NetMQ.Sockets;
using System;
using UnityEngine;
using System.Text.RegularExpressions;

/// <summary>
///     Example of requester who only sends Hello. Very nice guy.
///     You can copy this class and modify Run() to suits your needs.
///     To use this class, you just instantiate, call Start() when you want to start and Stop() when you want to stop.
/// </summary>
public class HelloRequester : RunAbleThread
{
    /// <summary>
    ///     Request Hello message to server and receive message back. Do it 10 times.
    ///     Stop requesting when Running=false.
    /// </summary>
    public static string messag = null;
    
    protected override void Run()
    {
        ForceDotNet.Force(); // this line is needed to prevent unity freeze after one use, not sure why yet
        using (RequestSocket client = new RequestSocket())
        {
            client.Connect("tcp://localhost:5555");
            byte[] message = new byte[100]; // Assuming a float is 4 bytes
            //string message = null;

            for (int i = 0;  Running; i++)
            {
                Debug.Log("Sending Hello");
                client.SendFrame("Hello");
                // ReceiveFrameString() blocks the thread until you receive the string, but TryReceiveFrameString()
                // do not block the thread, you can try commenting one and see what the other does, try to reason why
                // unity freezes when you use ReceiveFrameString() and play and stop the scene without running the server
                //                string message = client.ReceiveFrameString();
                //                Debug.Log("Received: " + message);
                bool gotMessage = false;
 
                while (Running)
                {
                    //gotMessage = client.TryReceiveFrameString(out message); // this returns true if it's successful
                    gotMessage = client.TryReceiveFrameBytes(out message);

                    if (gotMessage) break;
                }

                if (gotMessage)
                {
                    Debug.Log("Received " + message);

    
                    Debug.Log(BitConverter.ToInt32(message, 0));


                }
            }
        }

        NetMQConfig.Cleanup(); // this line is needed to prevent unity freeze after one use, not sure why yet
    }

如果是double

python

    # 将float转化为bytes
    float_number = 3.1425
    bytes_value = struct.pack("d", float_number) # Big-endian format
    socket.send(bytes_value)

unity HelloRequester.cs

            byte[] message = new byte[8]; // Assuming a float is 4 bytes
----------

               Debug.Log(BitConverter.ToDouble(message, 0));

C#高级教程-字符串与正则表达式_c#正则表达式匹配字符串-CSDN博客

把字符串分隔

python

    distance = 10.125
    strs = "Elegance is the only beauty that never fades."
    dis = "the distance is %.3f meters. " % distance

    socket.send(dis.encode('utf-8') + b'\n' + strs.encode('utf-8'))

unity HelloRequester.cs

                if (gotMessage)
                {
                    Debug.Log("Received " + message);

                    //Debug.Log("Received " + message[4]);

                    string pattern = @"\d+.\d+";
                    string pattern = @"\S+";

                    MatchCollection matches = Regex.Matches(message, pattern);

                    foreach (Match match in matches)
                    {
                        //Console.WriteLine(match.Value);
                        Debug.Log(match.Value);
                    }

                    Debug.Log(BitConverter.ToInt32(message, 0));


                }

unity解析

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值