0

I am trying to write a simple message to a remote Server using Socket in Android, The remote server was provided to me, here is my attempt, it stops at out.write

@Override
protected String doInBackground(String... params) {
    String comment = params[0];
    Log.i(TAG_STRING, "Comment is " + comment);
    String response = null;
    Socket socket = null;
    try {
        socket = new Socket("www.regisscis.net", 8080);
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        DataInputStream in = new DataInputStream(socket.getInputStream());
        Log.i(TAG_STRING, "Calling Write");
        out.writeBytes(comment);
        out.flush();
        String resposeFromServer = in.readUTF();
        out.close();
        in.close();
        response = resposeFromServer;               
        socket.close();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;
}

Would anyone know what I am doing wrong,

1
  • 8080 thats the HTTP port so you need to send an HTTP request Commented Aug 16, 2014 at 16:21

1 Answer 1

2

Turns out that I to use out.println("message") instead of out.write("message") when I post to this server. So I have updated my method like so

@Override
protected String doInBackground(String... params) {
    String comment = params[0];
    String response = null;
    Socket socket = null;
    try {
        socket = new Socket("www.regisscis.net", 8080);
        if (socket.isConnected()) {
            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())), true);
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));
            Log.i(TAG_STRING, "Calling Write");
            out.println(comment);
            String resposeFromServer = in.readLine();
            out.close();
            in.close();
            response = resposeFromServer;               
            socket.close();
        } else {
            Log.i(TAG_STRING, "Socket is not connected");
        }

    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.