Advertisement
Bunny83

TCPImageClient

Jun 12th, 2020
2,146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.72 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Threading;
  3. using System.Net.Sockets;
  4. using System.IO;
  5. using System.Collections.Concurrent;
  6.  
  7. public class TCPImageStream : MonoBehaviour
  8. {
  9.     Thread m_NetworkThread;
  10.     bool m_NetworkRunning;
  11.     ConcurrentQueue<byte[]> dataQueue = new ConcurrentQueue<byte[]>();
  12.     private void OnEnable()
  13.     {
  14.         m_NetworkRunning = true;
  15.         m_NetworkThread = new Thread(NetworkThread);
  16.         m_NetworkThread.Start();
  17.        
  18.     }
  19.     private void OnDisable()
  20.     {
  21.         m_NetworkRunning = false;
  22.         if (m_NetworkThread != null)
  23.         {
  24.             if (!m_NetworkThread.Join(100))
  25.             {
  26.                 m_NetworkThread.Abort();
  27.             }
  28.         }
  29.     }
  30.     private void NetworkThread()
  31.     {
  32.         TcpClient client = new TcpClient();
  33.         client.Connect("127.0.0.1", 1234);
  34.         using (var stream = client.GetStream())
  35.         {
  36.             BinaryReader reader = new BinaryReader(stream);
  37.             try
  38.             {
  39.                 while (m_NetworkRunning && client.Connected && stream.CanRead)
  40.                 {
  41.                     int length = reader.ReadInt32();
  42.                     byte[] data = reader.ReadBytes(length);
  43.                     dataQueue.Enqueue(data);
  44.                 }
  45.             }
  46.             catch
  47.             {
  48.  
  49.             }
  50.         }
  51.     }
  52.  
  53.     public Material mat;
  54.     public Texture2D tex = null;
  55.  
  56.     void Update()
  57.     {
  58.         byte[] data;
  59.         if (dataQueue.Count > 0 && dataQueue.TryDequeue(out data))
  60.         {
  61.             if (tex == null)
  62.                 tex = new Texture2D(1, 1);
  63.             tex.LoadImage(data);
  64.             tex.Apply();
  65.             mat.mainTexture = tex;
  66.         }
  67.     }
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement