Reputation: 1128
I am creating a simple unity application using client-server arch. My application works fine as long as server is on. If by accident I try to run the client while server is not running, the unity app freezes.
I have also used connection timeout as suggested in various posts, but of no help.
void Awake () {
init ();
}
void init() {
IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse (serverHost), serverPort);
client = new Socket (endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try {
client.SendTimeout = 1000;
client.ReceiveTimeout = 1000;
client.Connect (endpoint);
error = "";
} catch(Exception e) {
error = e.Message;
new WaitForSeconds(1);
}
Any suggestions might be welcome.
Thanks.
Upvotes: 2
Views: 3680
Reputation: 125275
Your client is freezing because the socket blocks. Connection time out wont solve this problem either.
There are 2 ways I know to solve this problem.
First method is to use Thread to call that function that contains the network code so that it does not freeze.
Second method is to use Asynchronous socket. https://msdn.microsoft.com/en-us/library/fx6588te(v=vs.110).aspx
I will provide example of the first method as I consider that to be easier.
I don't have all your code so I will provide what I can.
Change your code to
using System;
using System.Threading;
bool connected = false;
void init() {
// Create a new Thread
new Thread (() =>
{
IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse (serverHost), serverPort);
client = new Socket (endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try {
client.SendTimeout = 1000;
client.ReceiveTimeout = 1000;
client.Connect (endpoint);
error = "";
connected = true;
} catch(Exception e) {
connected = false;
error = e.Message;
new WaitForSeconds(1);
}
}).Start(); // Start the Thread
}
This will create a new Thread and start the Thread. Inside that that Thread, it will the socket connect code without blocking your application.
Then you can check if you connected to server later on by doing
if(connected){
// ...
}
Make sure you include using System.Threading
;
If you plan on receiving data from the server, make sure to also do the same or it will block and hang your app.
All you have to do in your receiving function is to add:
new Thread (() =>
{
// .....You receiving code here
}).Start();
You can learn more about threading here http://www.albahari.com/threading/
Upvotes: 4