TAGS :Viewed: 10 - Published at: a few seconds ago

[ Java ServerSocket.accept(); makes Server or UnityScript Client crash ]

I'm making an MMORPG using java server and Unity(Javascript/Unityscript) client. On server side I have the following:

while(running){
        System.out.println("Waiting for new client to connect.");
        Socket socket = serverSocket.accept(); /*When another client tries to connect,
server stops at this line, "Client connected." is never printed.*/
        System.out.println("Client connected.");
        if(!running){
            System.out.println("Closing server..");
        }
        ClientListener listener = new ClientListener(socket);
        clients.add(listener);
        listener.start();
}

So when I first run the server and the client, it all works fine. When I then close the Client and try to run client again, Server stops at serverSocket.accept();. Meaning that either server can't take another Client or Client can't connect to server. I think it's on the server side, but I really don't have any idea what might be causing this.

private function ThreadListener(){
client = new TcpClient();
var port = 16304;

try{
    print("running..");
    client.Connect(IPEndPoint(IPAddress.Parse("127.0.0.1"), port));

    ns = client.GetStream();

     var data = new byte[1024];

     var waitCounter = 0;
     print("connection made");

     var read = 0;

     while(true){
        if(ns.CanRead){
            read = ns.Read(data, 0, data.Length);
            var word = System.Text.Encoding.ASCII.GetString(data, 0, read);
            Action(word);
        }
     }
}      
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();
}
}

NOTE! I know that this unity client is pretty badly coded and javascript isn't my strongest point. But I will focus more on making it more efficient and stuff once I just get it work.

Edit 1: The Client just freezes until I close the server and after a few seconds from closing the server, Client gives an error message telling that it couldn't connect to server.

Edit 2: I made a test client using java to make sure the problem isn't on the server side. And I was able to succesfully connect to server multiple times using that test Client. I think it's easier to get help for unity related stuff on their own forums so I'll move this question there. :)

Answer 1


The problem was on the Client -side (Javascript), when closing the Client, I forgot to close the ThreadListener() thread. So I made following function:

function OnApplicationQuit(){ //this is called before program is closed
running = false;
WorkerThread.Abort();
if(ns != null){
    ns.Close();
}
client.Close();
WorkerThread.Join();
WorkerThread = null;
}

and now it's working as it should.