hi I'm new on Android platform. I need to write a TCP/SSL client class in my app, which download text file with some c# server. I have created .cer file and bks file for ssl communication . Indeed I need to use socket class communication instead of HTTP or HTTPS communication. My android code is:
public class MainActivity extends Activity {
static String filename = null;
static Socket socket = null;
static Boolean flag = true;
Button GetServerData, Upload;
TextView textPort;
EditText et;
Context context;static final int SocketServerPORT = 8889;
static final String SocketServerIP = "169.254.80.80";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button GetServerData = (Button) findViewById(R.id.GetServerData);
GetServerData.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Intent i = new Intent(MainActivity.this, MyHttpClient.class);
// startActivity(i);
ClientRxThread clientRxThread = new ClientRxThread(
SocketServerIP, SocketServerPORT);
clientRxThread.start();}
});
}private class ClientRxThread extends Thread {
String dstAddress;
int dstPort;
ClientRxThread(String address, int port) {
dstAddress = address;
dstPort = port;
}
@Override
public void run() {
// Socket socket = null;
InputStream in;
int bufferSize = 0;
try {
socket = new Socket(dstAddress, dstPort);
File file = new File(Environment.getExternalStorageDirectory(),
"test.txt");
bufferSize = socket.getReceiveBufferSize();
in = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream output = new BufferedOutputStream(fos);
DataInputStream clientData = new DataInputStream(in);
byte[] buffer = new byte[bufferSize];
int read;
while ((read = clientData.read(buffer)) > 0) {// != -1) {
output.write(buffer, 0, read);
}
output.flush();
output.close();
socket.close();
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "Finished",
Toast.LENGTH_LONG).show();
}});
} catch (IOException e) {
e.printStackTrace();
final String eMsg = "Something wrong: " + e.getMessage();
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, eMsg,
Toast.LENGTH_LONG).show();
}
});
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}}