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;
}

@Override
public void run()
{
    String msg = "";
    while(!msg.equals("exit"))
    {
        try
        {
            if(is.available() >0)
            {
                int data =0;
                StringBuilder sb = new StringBuilder();
                while(data >=0)
                {
                    data = dIn.read();
                    char c = (char) data;
                    sb.append(c);
                }

                System.out.println(sb.toString());

            }

        }
        catch (IOException e) {
            done = true;
            e.printStackTrace();
        }
    }
}

}

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)
{
    this.se        

Answers


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

Search




Leave an answer