1st I need to apologize since this is similar to an earlier post, but lack of sleep combined with a launch deadline tomorrow have contributed to produce a perfect storm of fuzzy thinking!
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
http://stackoverflow.com/questions/41330771/use-unity-api-from-another-thread-or-call-a-function-in-the-main-thread/41333540#41333540
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 () {
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();
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();
}
}