在进行Matlab和unity联合仿真工作时候,我们需要在二者之间进行数据交互。这里我们介绍如何使用Matlab通过UDP协议向unity发送数据。
Matlab发送端代码
u1=udp('10.1.1.198','RemotePort',8849,'LocalPort',55000);% 设置要把数据发送
到的IP地址和端口
fopen(u1); % 打开端口
a=1234.56; % 一次发送6个数据示例
b=9654.78;
c=6677.32;
d=7831.21;
e=2564.89;
f=4638.54;
string =num2str([a,b,c,d,e,f]);% 把数据格式更改为字符串
fwrite(u1, string);% 把数据写入端口
disp("string="+string);% 命令窗口显示发送数据格式
fclose(u1);% 关闭端口
delete(u1);% 删除端口
clear u1;% 清理缓存
Unity接收端代码
这段代码是从网上找可以直接通用的,我增加了字符串数据分割提取和格式转换部分,用的时候主要根据需要设置下数据接收的IP端口,以及根据接收数据内容进行提取赋值等。
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
using System;
using System.Text.RegularExpressions;
using UnityEngine.UI;
public class UDPClient: MonoBehaviour
{
///
/// 获取当前毫秒
///
///
public static double CurrentMilliseconds
{
get
{
DateTime dt = DateTime.Parse("01/01/1970");
TimeSpan ts = DateTime.Now - dt;
return ts.TotalMilliseconds;
}
}
//以下默认都是私有的成员
//Socket socketSend; //发送socket
UdpClient socketSend;
IPEndPoint ipSend; //客户端端口
Socket socketReceive; //接收socket
IPEndPoint ipReceive; //服务端端口
List clientEnds; //客户端
string recvStr; //接收的字符串
string sendStr; //发送的字符串
byte[] recvData = new byte[1024]; //接收的数据,必须为字节
byte[] sendData = new byte[1024]; //发送的数据,必须为字节
int recvLen; //接收的数据长度
Thread connectThread; //连接线程
//输入框
public InputField thisField;
private Rect m_fps, m_dtime;
private GUIStyle m_style = new GUIStyle();//GUI界面
//初始化
void InitSocket()
{
//定义连接的服务器ip和端口,可以是本机ip,局域网,互联网
ipSend = new IPEndPoint(IPAddress.Parse("127.0.0.1"),8848);
//ipSend = new IPEndPoint(IPAddress.Parse("192.168.1.200"),50000);
//定义套接字类型,在主线程中定义
socketSend = new UdpClient();
//定义服务端
//定义侦听端口,侦听任何IP
ipReceive = new IPEndPoint(IPAddress.Any, 8849);
//定义套接字类型,在主线程中定义
socketReceive = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//服务端需要绑定ip
socketReceive.Bind(ipReceive);
//定义客户端
IPEndPoint senderReceive = new IPEndPoint(IPAddress.Any, 8849);
clientEnds = new List();
//开启一个线程连接,必须的,否则主线程卡死
connectThread = new Thread(new ThreadStart(SocketReceive));
connectThread.Start();
}
///
/// UDP发送数据基本方法
///
///
void SocketSend(string sendStr)
{
//清空发送缓存
sendData = new byte[1024];
//数据类型转换
sendData = Encoding.UTF8.GetBytes(sendStr);
//发送给所有服务端
socketSend.Send(sendData, sendData.Length, ipSend);
}
///
/// 发送数据
///
public void ToSendString()
{
if (thisField.text != "")
{
SocketSend(thisField.text);
}
}
//服务器接收
void SocketReceive()
{
//进入接收循环
while (true)
{
//对data清零
recvData = new byte[1024];
//获取客户端,获取客户端数据,用引用给客户端赋值
EndPoint clientEnd = new IPEndPoint(IPAddress.Any, 8849);
recvLen = socketReceive.ReceiveFrom(recvData, ref clientEnd);
clientEnds.Add(clientEnd);
//print("message from: " + clientEnd.ToString()); //打印客户端信息
//输出接收到的数据
recvStr = Encoding.ASCII.GetString(recvData, 0, recvLen);
string[] recvStrArray = Regex.Split(recvStr, "\s+", RegexOptions.IgnoreCase);
string str_x = recvStrArray[0];
string str_y = recvStrArray[1];
string str_z = recvStrArray[2];
string str_yaw = recvStrArray[3];
string str_rotateX = recvStrArray[4];
string str_rotateZ = recvStrArray[5];
float _x = float.Parse(str_x);
float _y = float.Parse(str_y);
float _z = float.Parse(str_z);
float _yaw = float.Parse(str_yaw);
float _rotateX = float.Parse(str_rotateX);
float _rotateZ = float.Parse(str_rotateZ);
Vector3 _tempPosition = new Vector3(_x, _y, _z); //此处将接收到的位置信息赋予_tempPosition
VehicleTransInfo.currentTime = CurrentMilliseconds;
VehicleTransInfo.currentTargetPosition = _tempPosition;
VehicleTransInfo.rotation_x = _yaw / Mathf.PI * 180f;
VehicleTransInfo.rotation_y = _rotateX / Mathf.PI * 180f;
VehicleTransInfo.rotation_z = _rotateZ / Mathf.PI * 180f;
}
}
//连接关闭
void SocketQuit()
{
//关闭线程
if (connectThread != null)
{
connectThread.Interrupt();
connectThread.Abort();
}
//最后关闭socket
if (socketReceive != null)
socketReceive.Close();
if (socketSend != null)
socketSend.Close();
}
// Use this for initialization
void Start()
{
InitSocket(); //在这里初始化
m_dtime = new Rect(0, 100, 100, 100);
m_style.fontSize = 30;
m_style.normal.textColor = Color.white;
}
void OnApplicationQuit()
{
SocketQuit();
}
void Update()
{
if (Input.GetKey(KeyCode.W))
{
connectThread.Start();
}
}
void OnGUI()
{
GUI.Label(m_dtime, "位置: " + recvStr, m_style);//帧数显示函数
}
public static string MidStrEx_New(string sourse, string startstr, string endstr)
{
Regex rg = new Regex("(?<=(" + startstr + "))[.\s\S]*?(?=(" + endstr + "))", RegexOptions.Multiline | RegexOptions.Singleline);
return rg.Match(sourse).Value;
}
}



