1

Hi I want to send a message using a socket I have this :

   import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView textResponse;
    EditText editTextAddress, editTextPort;
    Button buttonConnect, buttonClear;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editTextAddress = (EditText)findViewById(R.id.address);
        editTextPort = (EditText)findViewById(R.id.port);
        buttonConnect = (Button)findViewById(R.id.connect);
        buttonClear = (Button)findViewById(R.id.clear);
        textResponse = (TextView)findViewById(R.id.response);

        buttonConnect.setOnClickListener(buttonConnectOnClickListener);

        buttonClear.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                textResponse.setText("");
            }});
    }

    OnClickListener buttonConnectOnClickListener =
            new OnClickListener(){

                @Override
                public void onClick(View arg0) {
                    MyClientTask myClientTask = new MyClientTask(
                            editTextAddress.getText().toString(),
                            Integer.parseInt(editTextPort.getText().toString()));
                    myClientTask.execute();
                }};

    public class MyClientTask extends AsyncTask<Void, Void, Void> {

        String dstAddress;
        int dstPort;
        String response = "";

        MyClientTask(String addr, int port){
            dstAddress = addr;
            dstPort = port;
        }

        @Override
        protected Void doInBackground(Void... arg0) {

            Socket socket = null;

            try {
                socket = new Socket(dstAddress, dstPort);

                ByteArrayOutputStream byteArrayOutputStream =
                        new ByteArrayOutputStream(1024);
                byte[] buffer = new byte[1024];

                DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
                outputStream.writeUTF("Hello World!");

                // Read data
//                DataInputStream inputStream = new DataInputStream(socket.getInputStream());
//                message = inputStream.readUTF();

                // Shut down socket


                int bytesRead;
                InputStream inputStream = socket.getInputStream();

                while ((bytesRead = inputStream.read(buffer)) != -1){
                    byteArrayOutputStream.write(buffer, 0, bytesRead);
                    response += byteArrayOutputStream.toString("UTF-8");
                }
                OutputStream out = socket.getOutputStream();

                out.write("some data".getBytes());
                out.flush();
                socket.shutdownInput();
                socket.shutdownOutput();
                socket.close();

            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                response = "UnknownHostException: " + e.toString();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                response = "IOException: " + e.toString();
            }finally{
                if(socket != null){
                    try {
                        socket.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            textResponse.setText(response);
            super.onPostExecute(result);
        }

    }

}

When I click a button only connected to the server. It don't send a message. What I have to do for send something ? maybe a message "Hello world" ?

1
  • you are trying to read firstly, not to write: while ((bytesRead = inputStream.read(buffer)) != -1){ And only after reading, you try to write: out.write("some data".getBytes());. Your server might wait the data to write first, but you are reading data before writing. Commented Nov 15, 2016 at 11:48

1 Answer 1

1

I'm not sure what the point of your program is but your output and input system seems fairly messy. You need a DataOutputStream to send data and a DataInputStream to receive data from and to the socket.

I've attached the system I use which is a lot simpler:

try {
        // Establish connection
        Socket socket = new Socket("IP ADDRESS HERE", PORT_NUMBER);

        // Request data
        DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
        outputStream.writeUTF("Hello World!");

        // Read data
        DataInputStream inputStream = new DataInputStream(socket.getInputStream());
        message = inputStream.readUTF();

        // Shut down socket
        socket.shutdownInput();
        socket.shutdownOutput();
        socket.close();
    } catch (IOException io) {
        io.printStackTrace();
    }

NB: You can change readUTF to readByte or several other alternatives as appropriate.

Sign up to request clarification or add additional context in comments.

5 Comments

I edit my post could you tell me evry thing is correct ?
I would remove "OutputStream out = socket.getOutputStream(); out.write("some data".getBytes()); out.flush();" and use the DataOutputStream to send this. Also not sure why you are using bytes for everything. If you don't need to then you should change it to UTF as it looks like you're doing that anyway.
Ok know I have a question when I send DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream()); outputStream.writeUTF("Hello World!"); Server see this when I do this : String str = "Hello"; byte b = Byte.valueOf(str); outputStream.write(b); server don't see this
Try outputStream.writeByte(b); ?
It's possible you are not reading it correctly on the other side?

Your Answer

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