Hello,
I am currently trying to develop a plugin that will allow me to connect to an external application (located on an computer) and send data back and forth. Currently I have mostly done this with sockets. I send a handshake signal to my external program written in java, it sends a handshake signal back and all is well.
But when I wanted a dedicated thread to listen to the java application i ran into some problems. The problem is on the plugin side.
I currently have this code:
Debug.Log("KSPArduinoBridge: Beginning...");
//must wait for arduino connection signal from program
var handShakeInformation = new Dictionary<string, double>();
handShakeInformation["id"] = 0;
handShakeInformation["M1"] = 1;
handShakeInformation["M2"] = 2;
handShakeInformation["M3"] = 3;
sendPacketToKSPMiddleMan(ConvertDictionaryToSend(handShakeInformation));
Debug.Log("KSPArduinoBridge: waiting");
Thread.Sleep(1000);
Debug.Log("KSPArduinoBridge: Making new thread for listening");
//MiddleManListener mml = new MiddleManListener();
Thread oThread = new Thread(ListenToMiddleMan);
Debug.Log("KSPArduinoBridge: Starting thread: ");
oThread.IsBackground = true;
oThread.Start();
Debug.Log("KSPArduinoBridge: past thread: ");
Thread.Sleep(5000);
I have gone through many iterations on this with different orders and ways of calling the thread. (so It may look a little messy and has lots of sleeps). The thread code is this:
public void ListenToMiddleMan()
{
Debug.Log("KSPArduinoBridge: thread started");
Socket javaProgram = KSPArduinoBridge.javaprogram;
Debug.Log("KSPArduinoBridge: java propgram grabbed");
while (true)
{
if (javaProgram.Available > 0)
{
byte[] rcvLenBytes = new byte[4];
javaProgram.Receive(rcvLenBytes);
int rcvLen = System.BitConverter.ToInt32(rcvLenBytes, 0);
byte[] rcvBytes = new byte[rcvLen];
javaProgram.Receive(rcvBytes);
String rcv = System.Text.Encoding.ASCII.GetString(rcvBytes);
Debug.Log("KSPArduinoBridge: Received input: " + rcv);
interpretInput(rcv);
}
}
}
It outputs all the debug logs outside of the ListenToMiddleMan thread, but never seems to enter the method itself.
Am I doing something wrong? I spent a few hours on this last night that I will never get back, so I thought I might ask for help since google wont help me either. Should I rethink even having a thread? Maybe just go with checking for items to read from the socket on update?
Source: https://github.com/FewCode/KSPArduinoBridge-KSP