我有一个matlab客户端,应该在"实时"通过tcp / ip协议到Unity 3D。虽然它可能不是最好的解决方案,但我尝试过UDP和直接套接字协议,但我不能让它们工作。
现在,我有一个测试代码,其中matlab生成一个随机数,并尝试尽可能快地将它发送到统一,问题是该数字被发送得太快,以至于Unity在发送之前打开套接字(来自matlab)...所以我在matlab中得到一个错误:"使用icinterface / fopen时出错(第83行) 不成功打开:连接被拒绝:连接"
我读过这些帖子,但我看不到通过tcp / ip修复它的方法:
Thread1 Thread2 Thread3 Thread4
这是我的matlab代码:
function chatWUMP()
i=0;
%connect to server (in this case Unity 3D)
tcpipClient = tcpip('127.0.0.1',55001,'NetworkRole','Client');
%set failed communication time
set(tcpipClient,'Timeout',30);
%for puredata
% pdClient = tcpip('127.0.0.1',3000);
% set(pdClient,'Timeout',30);
while (i<=160)
i = i+1;
phonecall;
%if the pause is less than .60 the program crashes because it can't
%connect back to the tcp/ip server :(
pause(.010);
end
function phonecall()
%open socket and write a message
fopen(tcpipClient);
a =rand;
b=num2str(a);
%send it to unity
fwrite(tcpipClient,b);
%stop communication
fclose(tcpipClient);
end
end
这是我从另一个线程修改的unity3d代码:
using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Linq;
using System;
using System.IO;
using System.Text;
public class readSocket : MonoBehaviour {
public float Int2send;
// Use this for initialization
TcpListener listener;
String msg;
void Start () {
listener=new TcpListener (55001);
listener.Start ();
print ("is listening");
}
// Update is called once per frame
void Update () {
if (!listener.Pending ())
{
int i = 0;
while (i < 300) {
i = i + 1;
}
}
else
{
//print ("socket comes");
TcpClient client = listener.AcceptTcpClient ();
NetworkStream ns = client.GetStream ();
StreamReader reader = new StreamReader (ns);
msg = reader.ReadToEnd();
float Intmsg;
// attempt to parse the value using the TryParse functionality of the integer type
//double.TryParse(msg, out Intmsg);
Intmsg = float.Parse(msg,System.Globalization.CultureInfo.InvariantCulture);
Int2send = Intmsg;
//print (Int2send);
//print (msg);
}
//print (Int2send);
}
}
原始代码来自:here