Home Ask Login Register

Developers Planet

Your answer is one click away!

cezarg February 2016

Java simple Client Server communication on Sockets

I'am trying to write an app for Android to connect to my Java Server and remotely Controll it (just run Media Player or sth like that). As I have never write any Socket Connection i thought that i should start with something really simple - just send short messages. And my problem is that first message which i send is ok. And when i try to send another message it doesnt came to server. Here is me code Client.java

public class Client implements Runnable
    private Socket connection;
    private Long id;
    private InputStream is;
    public Boolean done;
    DataInputStream dIn ;

public Client(Socket conn, Long ids) throws IOException
    connection = conn;
    is = conn.getInputStream();
    id = ids;
    dIn = new DataInputStream(is);
    done = false;

public Socket getConnection()
    return connection;
public void setConnection(Socket connection)
    this.connection = connection;

public Long getId()
    return id;
public void setId(Long id)
    this.id = id;

public void run()
    String msg = "";
            if(is.available() >0)
                int data =0;
                StringBuilder sb = new StringBuilder();
                while(data >=0)
                    data = dIn.read();
                    char c = (char) data;



        catch (IOException e) {
            done = true;


Now Server.java

package tcp;

public class Server implements Runnable {

private ServerSocket serverSocket;
private final static int SERVER_PORT = 6879;
private ServerManager serverManager;
InputStreamReader inputStreamReader;
BufferedReader bufferedReader;

public Server(ServerManager serverManager)


EJP February 2016

You're closing the connection after sending a single message. You therefore need to open a new connection to send a new message. Or else adjust your protocol at both ends so as to keep the connection open.

Post Status

Asked in February 2016
Viewed 1,391 times
Voted 8
Answered 1 times


Leave an answer

Quote of the day: live life