0

I have successfully reduced another TCP Socket Server example and confirmed that it works. I can see my connection messages in the Unity Console. However, I think I have an issue where I cannot implement this in my main application because of a threading issue.

How can I modify the following so that the contents of Update1 can communicate with my main Unity application? I attempted to implement a UnityThread solution but it just hangs my editor!

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Text;
using System;
using System.Threading;

public class TCPServer2 : MonoBehaviour {

  public bool isConnection, senddata1, senddata2, valuechanged, valuechanged2;

  public Thread mThread;
  public TcpListener server;
  public TcpClient client;
  public NetworkStream stream;
  byte[] msg1;
  string toSend;
  bool available,  selection, endpointChanged, parsedata;
  public String data, prevdata;
  int q = 0;
  int FPS = 0;

  // Use this for initialization
  void Start () {
  UnityThread.initUnityThread();
  isConnection = false;
  senddata1 = false;
  senddata2 = false;
  //print ("StartThread");
  ThreadStart ts = new ThreadStart(Update1);
  mThread = new Thread(ts);
  mThread.Start();
  }

  void Update()
  {

  }

  void Update1()
  {
  server = null;
  try
  {
  Int32 port = 1234;
  server = new TcpListener(IPAddress.Any, port);

  // Start listening for client requests.
  server.Start();

  // Buffer for reading data
  Byte[] bytes = new Byte[256];
  String data = null;

  // Enter the listening loop.
  while (true)
  {
  Thread.Sleep(10);

  Debug.Log("Waiting for a connection... ");

  client = server.AcceptTcpClient();
  if (client != null)
  {

  Debug.Log("Connected!");

  }
  data = null;

  // Get a stream object for reading and writing
  stream = client.GetStream();
  //StreamWriter swriter = new StreamWriter(stream);
  int i;

  // Loop to receive all the data sent by the client.
  while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)

  {
  data = Encoding.ASCII.GetString(bytes, 0, i);
  Debug.Log("0 ASSERT Received: data = " + data);

  switch (data)
  {
  case "TRIGGER":
  Debug.Log(":::::::::::::::1 ASSERT TRIGGER RECEIVED");

  /*
  toSend = "RECEIVED";

  msg1 = System.Text.Encoding.ASCII.GetBytes(toSend);
  stream.Write(msg1, 0, msg1.Length);
  */
  //stream.Flush();
  break;
  case "Disconnect":
  goto q;

  default:
  prevdata = "RECEIVED_NO_TRIGGER";
  byte[] msg = System.Text.Encoding.ASCII.GetBytes(prevdata);

  // Send back a response.
  stream.Write(msg, 0, msg.Length);

  break;
  }
  }
  q:
  // Shutdown and end connection
  client.Close();
  }

  }
  catch (SocketException e)
  {
  Debug.LogError("SocketException:" + e);
  }
  finally
  {
  // Stop listening for new clients.
  server.Stop();
  }

  }
  void OnApplicationQuit()
  {
  server.Stop();
  mThread.Abort();
  }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Bachalo
  • 6,965
  • 27
  • 95
  • 189
  • Have you tried setting thread to background? – mrogal.ski Feb 02 '17 at 21:27
  • Please read my entire post. I DID try implementing the UnityThread solution. Could someone possibly help with the proper implementation? I tried several variations but they all hang my editor. Where exactly should I put the UnityThread.executeInUpdate(() => method call? – Bachalo Feb 02 '17 at 21:32
  • *"TCP SocketServer works but does not execute on Main Thread"* That's right. Your server is not running on Main Thread and should not be running on the Main Thread. The code above is not freezing on my computer. Please make sure that the script is saved. Restart Unity and the Visual Studio – Programmer Feb 02 '17 at 21:35
  • You **only** use `UnityThread.executeInUpdate(() =>` when you need to call a Unity API from another Thread that is **not** the main Thread. In this case, your other `Thread`(mThread) is running in the `Update1` function. Anytime you want to call any Unity API from the `Update1` function, let's say update a UI Text, you do `UnityThread.executeInLateUpdate(()=> { yourText.text = "Score: 100"; });`. You won't get error with that. – Programmer Feb 02 '17 at 21:48
  • 1
    ok, think I understand now. THANKS! – Bachalo Feb 02 '17 at 22:00
  • Meta advice: please try to avoid responses like "Please read my entire post". Most people believe they _have_ read the whole post, and suggestions otherwise will sound rather similar to "can you read", which is perhaps more hostile than you intended. Hope that helps! – halfer Feb 05 '17 at 14:58

0 Answers0