0

I'm creating a android server client chat app using socket programming. Till now in my app the client messages will only display in the server. messages from server is not displaying. i'm attaching the java code only because i think from that u will get an idea about the xml layout components.

server.java

package com.example.androidsocketserver;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
 public class Server extends ActionBarActivity {
    private ServerSocket serverSocket;
    private Button btn;
    private boolean willsendMsg = false;
    Handler handler;
    Thread serverThread = null;
    public static final int serverPort = 6000;
    public static String SERVERIP = "10.0.2.15";
    TextView serverStatus;
    TextView text;
     EditText msgg;
    protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_server);
        serverStatus = (TextView)findViewById(R.id.status);
        text = (TextView)findViewById(R.id.chatt);
       msgg = (EditText)findViewById(R.id.mesg);
       btn = (Button)findViewById(R.id.send);
            btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            willsendMsg = true;
        }
        });
       handler = new Handler();
       this.serverThread = new Thread(new ServerThread());
       this.serverThread.start();
    }


 public class ServerThread implements Runnable{
   Socket socket = null;
    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {
            serverSocket = new ServerSocket(serverPort);
            while(true){
                socket = serverSocket.accept();
                handler.post(new Runnable(){
                    public void run(){
                        serverStatus.setText("New Connection accepted,and the address is" + socket.getInetAddress() + ", and the port is " + socket.getLocalPort());
                    }
                });

                CommunicationThread comm = new CommunicationThread(socket);
                new Thread(comm).start();
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            handler.post(new Runnable() {
                @Override
                public void run() {
                    serverStatus.setText("Couldn't detect internet connection.");
                }
            });
            e.printStackTrace();
        }

    }

}

public class CommunicationThread implements Runnable{
    private Socket client;
    BufferedReader input;
    String chat = msgg.getText().toString();
    public CommunicationThread(Socket clientt){
        this.client = clientt;
        try {

            this.input = new BufferedReader(new InputStreamReader(client.getInputStream()));
            if(willsendMsg){
                willsendMsg=false;
                OutputStream outputSteam = client.getOutputStream();
                PrintWriter pw = new PrintWriter(outputSteam, true);
                pw.println(chat);
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(!Thread.currentThread().isInterrupted()){
            try {
                final String read = input.readLine();
                handler.post(new Runnable(){
                    public void run(){
                        text.setText(text.getText().toString()+"Client :"+read+"\n");
                    }
                });
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

protected void onStop() {
    super.onStop();
    try {
        serverSocket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
  }
}

the Client.java

package com.example.androidclientsocket;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
 import android.support.v7.app.ActionBarActivity;
 import android.os.Bundle;
 import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
 import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class Clientsocket extends ActionBarActivity {
  private Socket socket;
  private static final int serverIPPort = 5000;
  private static String server_IP = "10.0.2.2";
  Handler handlers;
  TextView inb;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_clientsocket);
    inb = (TextView)findViewById(R.id.inbox);
    handlers = new Handler();
    new Thread(new ClientThread()).start();
    }
   public class ClientThread implements Runnable{

      @Override
          public void run() {
    // TODO Auto-generated method stub
     try {
    InetAddress serverAdd = InetAddress.getByName(server_IP);
    socket = new Socket(serverAdd,serverIPPort);
    BufferedReader inputt = new BufferedReader(new      InputStreamReader(socket.getInputStream()));
      final String box = inputt.readLine();
      handlers.post(new Runnable(){
        public void run(){
            inb.setText(inb.getText().toString()+"Server :"+box+"\n");
        }
        });
      } catch (UnknownHostException e) {
       // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
     }  

   }

 }

 public void Posting(View v){
  EditText et = (EditText)findViewById(R.id.msg);
    String message = et.getText().toString();
    try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
    out.println(message);
    et.setText("");
    } catch (UnknownHostException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    } catch (Exception e) {
    e.printStackTrace();
    }
 }

    protected void onStop() {
    super.onStop();
    try {
        socket.close();
    } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

the logcat didn't shows any exceptions or errors on button click. I have already added internet and access network permissions in manifest files. please help me to find the problem which causes the server message from not sending to client and displaying there.

user3493407
  • 37
  • 1
  • 8
  • Start with willsendMsg true. – greenapps Sep 11 '14 at 19:41
  • @greenapps: i tried but that also didn't worked – user3493407 Sep 12 '14 at 06:49
  • `Till now in my app the client messages will only display in the server.`. ? Your client isn't sending anything. It just starts to read. Are you sure the client connects? You are using two emulators on the same pc? – greenapps Sep 12 '14 at 07:14
  • So upon a new client connects the server will immediately send a message. But only if willsendMsg is true. After that it will go in a loop reading line by line. Why is there a willsendMsg boolean? – greenapps Sep 12 '14 at 07:19
  • I think you will have exceptions. How do you manage to get logcats from two emulators? You will get an exception there where the server sends the first message (if willsendMsg). That will cause for a NetworkOnMainThreadException. Put that code in the run() method of the thread too. – greenapps Sep 12 '14 at 07:32
  • `Okay for checking the code more easier..`. Please remove that. Don't post the same code twice. – greenapps Sep 12 '14 at 07:34
  • @greenapps: Hi greenapps , i worked this code in 2 emulators with separate port numbers using these operations " telnet localhost 5554" and "redir add tcp:5000:6000" . 5554 emulator is the server with port number 6000 and 5556 is the client with port number 5000. i got the client message on the server screen. – user3493407 Sep 12 '14 at 09:23
  • could u please help me to fix that willsendMsg by explaining a little more. i didn't get ur comments above. – user3493407 Sep 12 '14 at 09:24

0 Answers0