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.

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.