java – How to open Socket using ip and port which user enters

Question:

There is a client with a button button and two text input fields IpAddress and NewPort .

Help me to make it so that by pressing the button, read the data entered in IpAddress and NewPort and start the Socket using this data. The program itself is tested and works if ip and port set in the code.

Button button;
TextView IpAddress;
TextView NewPort;

private Socket socket;

private int SERVERPORT = 0;
private String SERVER_IP = null;

ClientThread client;

@Override
public void onCreate(Bundle.savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

button = (Button) findViewById(R.id.button);
IpAddress = (TextView) findViewById(R.id.IpAdd);
NewPort = (TextView) findViewById(R.id.PortAdd);

button.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
       SERVER_IP = IpAdress.getText().toString();
       SERVERPORT = NewPort.getText().length();

       client = new ClientThread();
       Thread thread = new Thread(client);
       thread.start();
    }
});


class ClientThread implements Runnable {
PrintWriter out;

@Override
public void run() {
            try {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
                socket = new Socket(serverAddr, SERVERPORT);

                out = new PrintWriter(socket.getOutputStream(), true);
            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
}

public void sendMessage(String str) {
    out.write(str);
    out.flush();
}
}

Answer:

Use EditText to enter data.

EditText editTextIp;
EditText editTextPort;

SERVER_IP = editTextPort.getText().toString();
SERVERPORT = Integer.parseInt(editTextPort.getText().toString());
Scroll to Top