问题描述:

I am new to Android/Java and hoping to get some help on a modification I am trying to make to sample code. I found an example for how to make a simple TCP/IP Client here (http://android-er.blogspot.com/2014/02/android-sercerclient-example-client.html). It works like a charm and I am able to establish a connection with the server. I am trying to modify the code to add buttons that can disconnect from the server, send a data, and display data coming in.

I am having trouble with the first modification where pressing the Disconnect (Clear in the example) button should disconnect the client on my app from the server. Rooting around the code, I figure I will need to use the socket.close() command. My problem is that the socket is being created in the onClick for the Connect button and I believe I need to link the socket.close() command in the onClick for the Disconnect button to that. How would I go about this? Do I place a reference to it in the onClick (method?) for Disconnect button? Alternatively, do I place the whole onClick for the Disconnect button inside the onClick for the COnnect button so it would recognize the socket reference? Is it just as simple as getting the onClick for Disconnect out of the onCreate? Finally, is there a fourth way to do this that I am not even seeing?

I realize how basic these questions are but, as I mentioned, I am new to Android and Java so am just trying to move through my first app with advice from the community. The good news is I think that if I can get a grasp on this button and how to reference the socket being created, the others will be much easier to navigate. The code in my MainActivity and Fragment are posted below.

MainActivity:

package com.example.androidclient;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.Socket;

import java.net.UnknownHostException;

import android.os.AsyncTask;

import android.os.Bundle;

import android.support.v7.app.ActionBarActivity;

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 ActionBarActivity {

TextView textResponse;

EditText editTextAddress, editTextPort;

Button buttonConnect, buttonDisconnect;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.fragment_main);

editTextAddress = (EditText)findViewById(R.id.address);

editTextPort = (EditText)findViewById(R.id.port);

buttonConnect = (Button)findViewById(R.id.connect);

buttonDisconnect = (Button)findViewById(R.id.disconnect);

textResponse = (TextView)findViewById(R.id.response);

buttonConnect.setOnClickListener(buttonConnectOnClickListener);

buttonDisconnect.setOnClickListener(new OnClickListener(){

@Override

public void onClick(View v) {

textResponse.setText("");

}});

}

OnClickListener buttonConnectOnClickListener = new OnClickListener(){

@Override

public void onClick(View arg0) {

MyClientTask myClientTask = newMyClientTask(editTextAddress.getText().toString(),Integer.parseInt(editTextPort.getText().toString()));

myClientTask.execute();

}

};

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

String IPaddress;

int Port;

String response = "";

MyClientTask(String addr, int port){

IPaddress = addr;

Port = port;

}

@Override

protected Void doInBackground(Void... arg0) {

Socket socket = null;

try {

socket = new Socket(IPaddress, Port);

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024);

byte[] buffer = new byte[1024];

int bytesRead;

InputStream inputStream = socket.getInputStream();

/*

* notice:

* inputStream.read() will block if no data return

*/

while ((bytesRead = inputStream.read(buffer)) != -1){

byteArrayOutputStream.write(buffer, 0, bytesRead);

response += byteArrayOutputStream.toString("UTF-8");

}

}

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

}

}

}

Fragment:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:orientation="vertical"

tools:context=".MainActivity" >

<EditText

android:id="@+id/address"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="IP Address" />

<EditText

android:id="@+id/port"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:hint="Port" />

<Button

android:id="@+id/connect"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Connect"/>

<Button

android:id="@+id/stop_test"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Stop Test"/>

<Button

android:id="@+id/disconnect"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="Disconnect"/>

<TextView

android:id="@+id/response"

android:layout_width="wrap_content"

android:layout_height="wrap_content"/>

</LinearLayout>

Any and all advice is greatly appreciated.

Hope to hear from you,

Yusif Nurizade

相关阅读:
Top