python
# 服务器端代码
import socket
import random
import struct
import time
# 创建一个服务器Socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 监听的地址和端口
host = '127.0.0.1'
port = 12345
# 绑定地址和端口
server_socket.bind((host, port))
# 开始监听连接
server_socket.listen(1)
# 等待客户端连接
client_socket, addr = server_socket.accept()
print('连接来自:', addr)
try:
# 发送和接收数据
while True:
data = client_socket.recv(1024).decode('utf-8')
if not data:
break
print('接收到数据:', data)
# client_socket.sendall('已收到数据'.encode('utf-8'))
time.sleep(0.5)
distance = random.uniform(0, 1)
# distance = 3.1415926
print(distance)
strs = "Elegance is the only beauty that never fades."
dis = "the distance is %.3f meters. " % distance
# client_socket.send(dis.encode('utf-8') + b'\n' + strs.encode('utf-8'))
bytes_value = struct.pack("d", distance) # Big-endian format
client_socket.send(bytes_value)
print('已发送数据:', dis)
except ConnectionResetError:
print("Unity客户端关闭连接")
finally:
# 关闭连接
client_socket.close()
server_socket.close()
unity3d
RecvData.cs
// Unity 3D客户端代码
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine;
public class RecvData : MonoBehaviour
{
// 服务器地址和端口
private string serverAddress = "127.0.0.1";
private int port = 12345;
// 与服务器的连接
private TcpClient client;
private NetworkStream stream;
private bool isConnect = false;
byte[] receiveBuffer = new byte[1024];
public static double dis_value = -1.0f;
// Start is called before the first frame update
void Start()
{
// 连接到服务器
ConnectToServer();
}
// Update is called once per frame
void Update()
{
if(isConnect)
{
SendDataToServer("Hello Server");
Debug.Log(ReceiveDataFromServer()); ;
}
}
// 连接到服务器
private void ConnectToServer()
{
try
{
client = new TcpClient(serverAddress, port);
stream = client.GetStream();
isConnect = true;
Debug.Log("成功连接到服务器");
}
catch (Exception e)
{
Debug.Log("无法连接到服务器:" + e);
}
}
// 发送数据到服务器
public void SendDataToServer(string data)
{
if (stream != null)
{
byte[] byteData = Encoding.UTF8.GetBytes(data);
stream.Write(byteData, 0, byteData.Length);
Debug.Log("已发送数据到服务器:" + data);
}
else
{
Debug.Log("无法发送数据,连接未建立");
}
}
// 从服务器接收数据
public string ReceiveDataFromServer()
{
try
{
int bytesRead = stream.Read(receiveBuffer, 0, receiveBuffer.Length);
//Debug.Log("bytesRead is " + bytesRead);
dis_value = BitConverter.ToDouble(receiveBuffer, 0);
print("dis_value is " + dis_value);
return dis_value.ToString();
}
catch (Exception e)
{
Debug.Log("接收数据时发生异常:" + e);
return null;
}
}
// 关闭连接
private void OnApplicationQuit()
{
if (stream != null)
{
stream.Close();
}
if (client != null)
{
client.Close();
}
}
}
需要导入xchart绘图package
ValueChat.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using XCharts.Runtime;
public class ValueChat : MonoBehaviour
{
public double distance_gap = 0.0f;
LineChart gap_chart = null;
private float timeBetweenGenerations = 0.01f; // 两次生成之间的时间间隔
private bool isShow = false; // 标记当前是否正在生成物体
public Text gapValue_text;
// Start is called before the first frame update
void Start()
{
SetValue_Show();
StartCoroutine("ShowData"); // 调用协程函数
}
// Update is called once per frame
void Update()
{
if (RecvData.dis_value != -1.0f)
{
//distance_gap = double.Parse(HelloRequester.gap_value);
distance_gap = RecvData.dis_value;
string formattedNumber = distance_gap.ToString("0.000");
gapValue_text.text = "The gap value is " + formattedNumber + " mm";
}
//distance_gap = double.Parse(HelloRequester.gap_value);
}
IEnumerator ShowData()
{
while (true)
{
if (!isShow)
{
yield return new WaitForSeconds(timeBetweenGenerations); // 等待指定的时间间隔后再进行下一次生成
Show_Line(gap_chart);
isShow = true; // 设置为正在生成状态
}
else
{
yield return null; // 不进行任何操作直到下一次生成
isShow = false; // 设置为正在生成状态
}
}
}
void SetValue_Show()
{
var chart = gameObject.GetComponent<LineChart>();
if (chart == null)
{
chart = gameObject.AddComponent<LineChart>();
chart.Init();
}
gap_chart = chart;
//设置标题:
var title = chart.EnsureChartComponent<Title>();
title.text = "Gap Value Line";
//设置提示框和图例是否显示:
var tooltip = chart.EnsureChartComponent<Tooltip>();
tooltip.show = true;
var legend = chart.EnsureChartComponent<Legend>();
legend.show = false;
//设置坐标轴:
var xAxis = chart.EnsureChartComponent<XAxis>();
xAxis.splitNumber = 10;
xAxis.boundaryGap = true;
xAxis.type = Axis.AxisType.Category;
var yAxis = chart.EnsureChartComponent<YAxis>();
yAxis.type = Axis.AxisType.Value;
//清空默认数据,添加Line类型的Serie用于接收数据:
chart.RemoveData();
chart.AddSerie<Line>("line");
添加10个数据:
//for (int i = 0, j = 1 ; i<60 ; i = i + 5, j++)
// {
// chart.AddXAxisData("T " + j);
// //chart.AddData(0, Random.Range(10, 20));
// chart.AddData(0, distance_gap);
// Debug.Log("-----------" + distance_gap);
// }
}
void Show_Line(LineChart _gap)
{
_gap.AddData(0, distance_gap);
}
}
运行
修改图的坐标和平均数显示的小数点后位数。