I am trying to create a very-very simple server-client application in Android. The server is running on my pc, it was written in python. (just a simple while (true) loop which receives a string and responses with an other string.) The problem is in the Android client. So i tried to create a singleton class in a separate thread, which:
- create the socket
- connect to the socket
- is reachable from other activites
- write to socket
- read from socket
I try to write and read from an other asynctask. It is working until i try to write to the socket again. (1 write is ok, any other attempts are failed.) I do not get any exception, i checked if the socket closed or the writer null, etc. The message just not wrote to the socket.
What's wrong with this solution? :/
Could you please help me?
Here is the thread:
public class ConnectThread extends Thread
{
// singleton Part
private static class ThreadHolder {
static final ConnectThread instance = new ConnectThread();
}
public static synchronized ConnectThread getInstance(){
if(ThreadHolder.instance == null)
Log.d("mytag", "NEW INSTANCE CREATED");
// return (ThreadHolder.instance == null) ? ThreadHolder.instance = new ConnectThread() : ThreadHolder.instance;
return ThreadHolder.instance;
}
private ConnectThread(){
}
// implementation part
private Socket mSocket;
private BufferedWriter socketWriter;
private BufferedReader socketReader;
public Socket getSocket() {
return mSocket;
}
public void WriteToSocket(String msg)
{
try{
if(!(mSocket.isClosed()))
{
Log.d("mytag", "Writing to socket");
if(socketWriter == null)
Log.d("mytag", "Writer closed - in write to socket");
socketWriter.write(msg);
socketWriter.flush();
}else
Log.d("mytag", "CANT write to socket");
}catch(IOException e)
{
e.printStackTrace();
Log.d("mytag", e.toString());
}
}
public String ReadFromSocket()
{
try
{
if(!(mSocket.isClosed())) {
Log.d("mytag", "Reading from socket");
if(socketReader == null)
{
Log.d("mytag", "Reader closed - in read from socket");
}
return socketReader.readLine();
}else
{
Log.d("mytag", "CANT from socket");
return null;
}
}catch (IOException e)
{
e.printStackTrace();
return null;
}
}
@Override
public void run() {
try
{
mSocket = new Socket();
mSocket.setKeepAlive(true);
try
{
mSocket.setTcpNoDelay(true);
}
catch (SocketException e)
{
}
mSocket.connect(new InetSocketAddress("192.168.0.128", 8888), 2000);
if(!(mSocket.isClosed()))
{
Log.d("mytag", "SOCKET IS RUNNING");
socketWriter = new BufferedWriter(new OutputStreamWriter(this.mSocket.getOutputStream()));
socketReader = new BufferedReader(new InputStreamReader(this.mSocket.getInputStream()));
if(socketWriter == null)
{
Log.d("mytag", "WRITER NOT CREATED");
}else
Log.d("mytag", "WRITER READY");
if(socketReader == null)
{
Log.d("mytag", "READER NOT CREATED");
}else
Log.d("mytag", "READER READY");
}
}catch (IOException e)
{
e.printStackTrace();
}
}
}
And here are the attempts to read, write:
@Override
protected Void doInBackground(Void... params)
{
PrintDebugMsg("do in background");
//--------------------------------------------------------------------------------------
changeProgressMsg(progressDialog, "Checking network availability...");
//progressDialog.setTitle("Checking network availability...");
//check network:
ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(parentContext.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if(netInfo != null && netInfo.isConnected())
{
networkAvail = true;
response += "| Network available |";
}
PrintDebugMsg("do in background 2");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
changeStatusImg(imgvNetworkStatus, networkAvail?R.drawable.online:R.drawable.offline);
//--------------------------------------------------------------------------------------
changeProgressMsg(progressDialog, "Pinging server");
//progressDialog.setTitle("Pinging server...");
//check server status
try {
PrintDebugMsg("do in background 3");
if(!(ConnectThread.getInstance().getSocket().isClosed()))
{
ConnectThread.getInstance().WriteToSocket(PING_FROM_DROID);
String line = "";
line = ConnectThread.getInstance().ReadFromSocket();
if(line.equals(PING_ACK))
{
serverAvail = true;
response += " | pinged |";
PrintDebugMsg("do in background 4", true);
}
}
else{
response += " | NOT pinged |";
PrintDebugMsg("do in background 5", true);
throw new UnknownHostException();
}
PrintDebugMsg("do in background 6", true);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response += " | UnknownHostException: " + e.toString() + " - during server check |";
PrintDebugMsg("do in background 7", true);
} finally{
PrintDebugMsg("do in background 9", true);
if(ConnectThread.getInstance().getSocket() != null){
}
}
PrintDebugMsg("do in background 10", true);
if(serverAvail)
{
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
changeStatusImg(imgvServerStatus, serverAvail?R.drawable.online:R.drawable.offline);
//--------------------------------------------------------------------------------------
changeProgressMsg(progressDialog, "Connectiong to server...");
//connect to server:
try {
PrintDebugMsg("do in background 11",true);
//socket = new Socket(dstAddress, dstPort);
//socket = ConnectThread.getInstance().getSocket();
PrintDebugMsg("do in background 12",true);
if(!(ConnectThread.getInstance().getSocket().isClosed())) {
PrintDebugMsg("do in background 13",true);
PrintDebugMsg("do in background 14",true);
PrintDebugMsg("do in background 15",true);
ConnectThread.getInstance().WriteToSocket(CONN_REQ_FROM_DROID);
String line = "";
line = ConnectThread.getInstance().ReadFromSocket();
PrintDebugMsg("conn line = " + line, true);
if(line != null && line.equals(CONN_ACK))
{
connected = true;
response += "| connected |";
PrintDebugMsg("do in background 12");
}
}else
{
response += "| NOT connected |";
PrintDebugMsg("do in background 13");
throw new UnknownHostException();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response += " | UnknownHostException: " + e.toString() + " - during connecting |";
}finally{
PrintDebugMsg("connection finished");
}
if(connected) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
changeStatusImg(imgvConnectionStatus, connected?R.drawable.online:R.drawable.offline);
//--------------------------------------------------------------------------
------------
return null;
}
The "util" functions:
private void PrintDebugMsg(String msg, boolean b)
{
if(b)
Log.d("mytag", msg);
}
private void changeProgressMsg(final ProgressDialog dialog,final String value){
runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.setMessage(value);
}
});
}
private void changeStatusImg(final ImageView imgView, final int imgId){
runOnUiThread(new Runnable() {
@Override
public void run() {
imgView.setImageResource(imgId);
}
});
}