[Java for Android App Development] Av1vz:
SOLVED. please lock.

I have 2 buttons, Server and Client.

The server button contain a textview which prints stuff received from the client.

The client button open Editbox and Send button which uses OnClick function.

In debug mode everything works fine.

When I run them independently and playing with ON/OFF SocketServer and Existing/New SocketClient the program would mostly get stuck and sometimes i get flowed with "Client says: null"

It usually happens when I click in device1 on Server Button, in device2 on client -> send a message from device2 to device1 and it successes -> close server on device1 -> send about 3 messages on device2 (remember that the serverSocket is closed) -> open server on device1 -> close and open client on device2.

The app also getting stuck randomaly after some turn off screen and turn on using the power button while playing with buttons.. and I cant find the issue.

Server.java:

package com.example.socketproject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;

import org.apache.http.conn.util.InetAddressUtils;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class Server extends Activity
{
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
private final static int SECONDS_TO_WAIT = 1;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server);
text = (TextView) findViewById(R.id.textview_server);
updateConversationHandler = new Handler();
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.server, menu);
return true;
}

@Override
protected void onDestroy()
{
super.onDestroy();
try
{
if (!serverSocket.isClosed())
{
serverSocket.close();
}
if (!serverThread.isInterrupted())
{
serverThread.interrupt();
}
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " );
}
}

@Override
protected void onStop()
{
super.onStop();
try
{
if (!serverSocket.isClosed())
{
serverSocket.close();
}
if (!serverThread.isInterrupted())
{
serverThread.interrupt();
}
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " );
}
}

private class ServerThread implements Runnable
{
public void run()
{
boolean accepted = false;
InetSocketAddress socketAddr = new InetSocketAddress(59135);
try
{
serverSocket = new ServerSocket();
serverSocket.setReuseAddress(true);
serverSocket.setSoTimeout((int) TimeUnit.SECONDS.toMillis(SECONDS_TO_WAIT));
serverSocket.bind(socketAddr);
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " );
}
while (!Thread.currentThread().isInterrupted())
{
Socket socket = null;
try
{
socket = serverSocket.accept();
accepted = true;
}
catch (InterruptedIOException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
Thread.currentThread().interrupt();
}

if (accepted)
{
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
}

accepted = false;
}
}
}

private class CommunicationThread implements Runnable
{
private Socket clientSocket;
private BufferedReader input;

public CommunicationThread(Socket clientSocket)
{
this.clientSocket = clientSocket;
try
{
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " );
Thread.currentThread().interrupt();
}
}

public void run()
{
while (!Thread.currentThread().isInterrupted())
{
try
{
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " );
Thread.currentThread().interrupt();
}
}
}
}

private class updateUIThread implements Runnable
{
private String msg;
public updateUIThread(String str)
{
this.msg = str;
}

@Override
public void run()
{
text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
}
}
}

Client.java:

package com.example.socketproject;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.http.conn.util.InetAddressUtils;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

public class Client extends Activity
{
private final static int SECONDS_TO_WAIT = 5;

private PrintWriter out = null;
private Socket socket = null;
private ClientThread clientThread = new ClientThread();
private String serverIp = null;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
serverIp = MY_PHONE_IP_HERE;
}

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.client, menu);
return true;
}

private String getLocalIpAddress()
{
String ipAddr = null;
try
{
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();)
{
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
{
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress()) )
{
ipAddr = inetAddress.getHostAddress();
return ipAddr;
}
}
}
}
catch (SocketException ex)
{
Log.d(TAG, ex.toString());
}

return ipAddr;
}

public void onClick(View view)
{
try
{
ExecutorService poolExecutor = Executors.newSingleThreadExecutor();
poolExecutor.execute(clientThread);
poolExecutor.shutdown();
poolExecutor.awaitTermination(SECONDS_TO_WAIT, TimeUnit.SECONDS);
EditText et = (EditText) findViewById(R.id.editText_client);
String str = et.getText().toString();
if(out == null)
{
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
}
out.println(str);
}
catch (UnknownHostException e)
{
Log.e(TAG, e.getMessage() + " |||| " + e.getStackTrace());
}
catch (IOException e)
{
Log.e(TAG, e.getMessage() + " |||| " + e.getStackTrace());
}
catch (Exception e)
{
Log.e(TAG, e.getMessage() + " |||| " + e.getStackTrace());
}
}

class ClientThread implements Runnable
{
@Override
public void run()
{
try
{
InetAddress serverAddr = InetAddress.getByName(serverIp);
socket = new Socket();
socket.connect(new InetSocketAddress(serverAddr, 59135), (int) TimeUnit.SECONDS.toMillis(SECONDS_TO_WAIT));
//socket = new Socket(serverAddr, 59135);
}
catch (UnknownHostException e)
{
Log.e(TAG, e.getMessage() + " |||| " + e.getStackTrace());
}
catch (IOException e)
{
// TODO IF HOST ISNT EXIST
Log.e(TAG, e.getMessage() + " |||| " + e.getStackTrace());
}
}
}
}

EDIT:

nevermind, it was interrupt flag which was erased and made unexpected results with threads. decided to use booleans instead.