Advertisement
Guest User

C# TcpListener for communication with Processing...

a guest
Aug 1st, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.60 KB | None | 0 0
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Threading;     //
  5. using UnityEngine;          // Using Unity 2017.1.0f3
  6.                             //
  7.  
  8. //Called when the application started
  9. void Start()
  10. {
  11.  
  12.         //Create another thread for the networking (I don't want to block the main thread in C# too)
  13.         thisServer = new TcpListener(IPAddress.Any, PORT);
  14.         serverThreadStart = new ThreadStart(ServerThread);
  15.         serverThread = new Thread(serverThreadStart);
  16.  
  17.         //Start the TcpServer
  18.         serverThread.Start();
  19.  
  20. }
  21.  
  22. //The server thread
  23. void ServerThread() {
  24.  
  25.         //The reading buffer and the data
  26.         Byte[] bytes = new Byte[1024];
  27.         String data = null;
  28.  
  29.         //Wait for the client here after he is disconnected too
  30.         while (true) {
  31.  
  32.             //Try to accept the incoming client
  33.             connectedClient = thisServer.AcceptTcpClient();
  34.  
  35.             //Get a stream object for reading and writing
  36.             NetworkStream stream = connectedClient.GetStream();
  37.  
  38.             //The data size
  39.             int i;
  40.  
  41.             //Try to receive data from client while its connected to the server(this)
  42.             while (connectedClient.Connected) {
  43.  
  44.                 //Dont try with data encoding id its null
  45.                 if ((i = stream.Read(bytes, 0, bytes.Length)) != 0) {
  46.  
  47.                     //Get the track data and decode it / encode to ASCII
  48.                     data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
  49.                    
  50.                     Debug.Log(data /*The message from processing*/);
  51.  
  52.                 }
  53.  
  54.             }
  55.  
  56.         }
  57.  
  58.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement