TCP/IP 接收字节并转换为纹理



我有一个小问题。我有另一个程序/软件可以将图像转换为字节并发送它们。因此,我现在需要做的是在Unity中捕获这些字节并将它们转换回图像并将其设置为纹理。

我已经通过TCP/IP系统建立了与其他软件的连接,连接正在工作,其他软件正在发送数据,但我不知道如何将这些字节转换为img。

Debug.Log("client message received as: " + clientMessage);

只是一个测试,所以我可以看到数据正在通过。

这是我的代码

img.LoadRawTextureData(Loader);
img.Apply();
GameObject.Find("Plane").GetComponent<Renderer>().material.mainTexture = img;

//

private void ListenForIncommingRequests()
{
try
{           
tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 35800);
tcpListener.Start();
Debug.Log("Server is listening");
Byte[] bytes = new Byte[1024];
while (true)
{
using (connectedTcpClient = tcpListener.AcceptTcpClient())
{               
using (NetworkStream stream = connectedTcpClient.GetStream())
{
int length;                         
while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
{
var incommingData = new byte[length];
Array.Copy(bytes, 0, incommingData, 0, length); 
Loader = incommingData;
string clientMessage = Encoding.ASCII.GetString(incommingData);
Debug.Log("client message received as: " + clientMessage);                            
}
}
}
}
}
catch (SocketException socketException)
{
Debug.Log("SocketException " + socketException.ToString());
}
}

您是否尝试过将字节传递到 LoadRawTextureData 中?

private byte[] ListenForIncommingRequests()
{
try
{           
tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 35800);
tcpListener.Start();
Debug.Log("Server is listening");
Byte[] bytes = new Byte[1024];
while (true)
{
using (connectedTcpClient = tcpListener.AcceptTcpClient())
{               
using (NetworkStream stream = connectedTcpClient.GetStream())
{
int length;                         
while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
{
var incommingData = new byte[length];
Array.Copy(bytes, 0, incommingData, 0, length); 
Loader = incommingData;
string clientMessage = Encoding.ASCII.GetString(incommingData);
Debug.Log("client message received as: " + clientMessage);                            
}
}
}
}
}
catch (SocketException socketException)
{
Debug.Log("SocketException " + socketException.ToString());
}
return bytes;
}

并这样称呼它。

var result = ListenForIncommingRequests();
img.LoadRawTextureData(result);
img.Apply();
GameObject.Find("Plane").GetComponent<Renderer>().material.mainTexture = img;

最新更新