Jakub
Jakub

Reputation: 201

Application using socket freezes when it tries to connect to server

I am doing application which send some data from mobile phone to PC. Im using socket to do it. When the server is online it works, but when I try to connect with wrong ip/port or server is not running then application freezes and I cant do nothing. It because client on mobile phone tries to connect to server.

I have main class in which I make:

Thread cThread = new Thread( new TCPClient( ip, port, message, context) );
cThread.start();

There is context in new TCPClient because i need to make Toast when message is sent or when error appears. In TCPClient class there is:

public void run(){
try {
InetAddress serverAddr = InetAddress.getByName(s_ip);
Log.d("TCP", "C: Connecting...");
Socket socket = new Socket(serverAddr, s_port); 

When server is online it goes to:

Log.d("TCP", "C: Sending: '" + s_msg + "'");
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
out.println(s_msg);
Log.d("TCP", "C: Sent.");
Log.d("TCP", "C: Done.");

but when the server is offline or I put wrong ip/port my application freezes. I cant do nothing for a while.

Is there any solution to force stop trying connect to server after some time? For example after 5 second application will go to catch and give me error.

I tried to do this with AsyncTask, then application is working even when Client tries to connect to server, but toast with error appears after not acceptable time for me, so I would like a solution which will give me error when client cannot connect with server in for example 5 seconds.

Upvotes: 2

Views: 4432

Answers (2)

confucius
confucius

Reputation: 13327

Perhaps you didn't set a timeout connection so it's "0" by default which means that it will never timeout , so you can set the timeout to 1 minute it won't freeze for more than one minute .

Upvotes: 1

Tomik
Tomik

Reputation: 23977

You can set the connection timeout. You have to use different constructor of Socket class. Insead of:

Socket socket = new Socket(serverAddr, s_port); 

use:

Socket socket = new Socket();
socket.connect(new InetSocketAddress(serverAddr, s_port), 5000);

In case of timeout an exception is thrown.

Upvotes: 6

Related Questions