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解析