TCP-IP Connection between Matlab and Unity3D

It's a part of an effort to answer the question of Connection between Matlab and Unity3D from BAA
206 Downloads
Updated 13 Jul 2020

View License

You can check the real question from https://www.mathworks.com/matlabcentral/answers/196774-connection-between-matlab-and-unity3d

First*, Matlab as server and unity as client
// matlab code
clc
clear all
tcpipServer = tcpip('0.0.0.0',55000,'NetworkRole','Server');
while(1)
data = membrane(1);
fopen(tcpipServer);
rawData = fread(tcpipServer,14,'char');
for i=1:14 rawwData(i)= char(rawData(i));
end
fclose(tcpipServer);
end

// Unity C# code
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System;
using System.IO;
public class Socket : MonoBehaviour {
// Use this for initialization
internal Boolean socketReady = false;
TcpClient mySocket;
NetworkStream theStream;
StreamWriter theWriter;
StreamReader theReader;
String Host = "localhost";
Int32 Port = 55000;
void Start () {
setupSocket ();
Debug.Log ("socket is set up");
}
// Update is called once per frame
void Update () {
}
public void setupSocket() {
try {
mySocket = new TcpClient(Host, Port);
theStream = mySocket.GetStream();
theWriter = new StreamWriter(theStream);
socketReady = true;
//writeSocket("yah!! it works");
Byte[] sendBytes = Encoding.UTF8.GetBytes("yah!! it works"); //--> if the above line doesn't work use this line instead
mySocket.GetStream().Write(sendBytes, 0, sendBytes.Length); // with this one also
Debug.Log ("socket is sent");
}
catch (Exception e) {
Debug.Log("Socket error: " + e);
}
}
}

Second, unity as server and Matlab as client

//Unity C# code
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 {
// Use this for initialization
TcpListener listener;
String msg;
void Start () {
//listener=new TcpListener (55001);
listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 55001);
listener.Start ();
print ("is listening");
}
// Update is called once per frame
void Update () {
if (!listener.Pending ())
{
}
else
{
print ("socket comes");
TcpClient client = listener.AcceptTcpClient ();
NetworkStream ns = client.GetStream ();
StreamReader reader = new StreamReader (ns);
msg = reader.ReadToEnd();
print (msg);
}
}
}

//ivan camponogara on 2 Jun 2019
//1) Your unity C# code works only if you name it "readSocket" (as specified at line 10 of the code before the "MonoBehaviour" command.
//2) In the TcpListener command (line 20 of the code) within the parenthesis you have to specify the ip number in this way: IPAddress.Parse("127.0.0.1").
//Then you have to write the server port number (55001) separated by a comma.
listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 55001);
//3) The C# code in unity works only once you drag the C# file on the top the "Main Camera" file that you can find in the "Sample scene" file.

//Matlab code
clc
clear all
tcpipClient = tcpip('127.0.0.1',55001,'NetworkRole','Client');
set(tcpipClient,'Timeout',30);
fopen(tcpipClient);
a='yah!! we could make it';
fwrite(tcpipClient,a);
fclose(tcpipClient);

//in each implementation the server should runs first before the client otherwise you will get the below error
//Connection refused:in Matlab or remote machine actively refuse the connection in unity

Cite As

Larasmoyo Nugroho (2024). TCP-IP Connection between Matlab and Unity3D (https://www.mathworks.com/matlabcentral/fileexchange/75728-tcp-ip-connection-between-matlab-and-unity3d), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R2014a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
Version Published Release Notes
1.0.2

i put the matlab codes into two .m files :
1. server_matlab.m
2. client_matlab.m

1.0.1

i incorporate feedback

1.0.0