- Home /
JavaScript TcpClient().Connect freezes
I'm making an MMORPG using Unity. I'm using the following system to connect to Java server.
import System;
import System.Threading;
import System.Net;
import System.Net.Sockets;
private var WorkerThread : Thread;
private var client : TcpClient;
private var ns : NetworkStream;
function Start () {
WorkerThread = new Thread(ThreadListener);
WorkerThread.Start();
}
private function ThreadListener(){
client = new TcpClient();
var port = 16304;
try{
print("running..");
client.Connect(IPEndPoint(IPAddress.Parse("127.0.0.1"), port));
print("Connected..");
ns = client.GetStream();
var data = new byte[1024];
var waitCounter = 0;
print("connection made");
var read = 0;
while(true){
do{
try{
read = ns.Read(data, 0, data.Length);
var word = System.Text.Encoding.ASCII.GetString(data, 0, read);
Action(word);
}
catch(err){
print(err.Message);
}
} while(ns.CanRead);
}
}
catch (InvOpEx : InvalidOperationException) {
Debug.Log("TCP exception: " + InvOpEx.Message);
}
catch (SockEx : SocketException) {
Debug.Log("Socket exception: " + SockEx.Message);
}
finally {
if(ns != null)
ns.Close();
client.Close();
}
}
When I first run the game, it connects to server just fine and everything works as it should. When I then close the program and try to run it again, the whole Unity freezes. I'm sure the problem isn't on the server side (had to make a java coded client to make sure). If I then close the server when Unity is frozen, after a couple of seconds it just gives an error message saying that it couldn't connect to server. Any help is greatly appreciated.
Answer by YoungDeveloper · May 20, 2015 at 05:21 PM
I believe the WorkerThread will continue to work even if you close unity thread? Add OnDestroy and close the thread there, by setting some flag false, also add debugs to check do you even get to finally.
OnDestroy didn't seem to work but I succeeded using OnApplicationQuit ins$$anonymous$$d. Thank you for your help.
I wasn't sure the OnApplicationQuit works in editor. edit: i just tested OnDestroy, it works on editor stop, shouldn't be a problem.
Okay, well I think I'll still stick to OnApplicationQuit. It also seems to work on editor too :)
Your answer
Follow this Question
Related Questions
Unity socket connection 0 Answers
How to connect Node.js + Unity? 7 Answers
Socket connection on Android/IOS/Windows 1 Answer
MATLAB to Unity Port Connection 0 Answers
Problem sending array to unity player using SendMessage 1 Answer