DixE4 DixE4 - 3 years ago 112
Android Question

Socket.Close And Socket.Connect

I'm Creating an android studio app ...

My App have multiple forms(pages?) and a main form that connect to a socket server when started .

The problem is that it's giving:

java.net.socketexception : Socket is closed
.

Why?

I want to close the socket if its already connected so it wont connect multiple times and cause bugs. So I did:

if(!socket.isClosed()) {
socket.close();
}


Thread.sleep(300);


socket.connect(new InetSocketAddress(ip, port), 1000);

dos = new DataOutputStream(socket.getOutputStream());
dis = new BufferedReader(new InputStreamReader(socket.getInputStream()));


They are all in a Thread with a try catch

but it always go to catch :(

Note : It have to be Closed and reopened Because of some reasons... And I'm Using Hercules as server

Question: Why? how to make sure there will be no multiple connections ?

I've done:

if(socket.isConnected()) socket.close();

Thread.sleep(300);


socket.connect(new InetSocketAddress(ip, port), 1000);


dos = new DataOutputStream(socket.getOutputStream());
dis = new BufferedReader(new InputStreamReader(socket.getInputStream()));


full code :

package com.example.discopc.yubismart;

import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.Socket;


public class Main extends Activity {

DataOutputStream dos;
BufferedReader dis;
String ip;
int port;
public String name;
String rele;

public static Socket socket = new Socket();

String line;

public ImageButton mainb;
Boolean ison=false;

public TextView stat;

File file1;
File path1;

public ImageButton hexa,event,delay,charger,daily;

File file2;
File path2;
ProgressDialog dialog;
MediaPlayer mp = new MediaPlayer();


boolean isfade; boolean isc;boolean waiter;
@Override
public void onBackPressed() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


mainb=(ImageButton)findViewById(R.id.main);
stat=(TextView)findViewById(R.id.Stat);
final Button ret =(Button)findViewById(R.id.ret);

ip= List1.Fip;
port= List1.Fport;
name= List1.Fname;
rele= List1.Frele;

dialog = new ProgressDialog(this); // this = YourActivity
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Loading. Please wait...");
dialog.setIndeterminate(true);
dialog.setCanceledOnTouchOutside(false);
dialog.show();

hexa=(ImageButton)findViewById(R.id.hexa);
delay=(ImageButton)findViewById(R.id.delay);
charger=(ImageButton)findViewById(R.id.charger);
event=(ImageButton)findViewById(R.id.event);
daily=(ImageButton)findViewById(R.id.daily);

rele = rele.replace("Rel", "Sw");
rele = rele.replaceAll("[^\\d]", "");
rele = rele.replace(" ", "");

isfade=true;
ffout();
isc=false;
waiter=true;

ret.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {


startActivity(new Intent(Main.this,Home.class));
}


});

delay.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
if(!isfade){
startActivity(new Intent(Main.this,Delay.class));
}
}


});
event.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
if(!isfade){
startActivity(new Intent(Main.this,Event.class));
}
}


});
charger.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
if(!isfade){
startActivity(new Intent(Main.this,Charger.class));
}
}


});
hexa.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {

new Thread(new Runnable() {
public void run() {
if(waiter){
if(isfade) {spinX();
waiter=false;
isfade=false;
in();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
waiter=true;

}else{spinP();
isfade=true;
out();
waiter=false;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
waiter=true;

}
}


}}).start();
}


});


new Thread(new Runnable() {
public void run() {
try {



try {
if(!socket.isClosed()) {
socket.close();
}
} catch (IOException e2) {
// e2.printStackTrace();
}

Thread.sleep(300);


socket.connect(new InetSocketAddress(ip, port), 1000);

dos = new DataOutputStream(socket.getOutputStream());
dis = new BufferedReader(new InputStreamReader(socket.getInputStream()));

oc1();
Main.this.runOnUiThread(new Runnable() {
public void run() {
try {
stat.setText("وصل شدیم به "+"\n"+name+" : "+rele);
stat.setTextColor(Color.GREEN);
dialog.dismiss();
isc=true;
ActiveRec();
} catch (Exception e) {} }
});

} catch (Exception e) {
try {
final String error=e.toString();
Main.this.runOnUiThread(new Runnable() {
public void run() {
try {
stat.setText("نمیتونم وصل شم به "+"\n"+name+" : "+rele+"\n"+ip+":"+port+"\n"+error.toString());
stat.setTextColor(Color.RED);
isc=false;
dialog.dismiss();
} catch (Exception e) {} }
});

faild();

} catch (IOException e1) {
try {
socket.close();
} catch (IOException e2) {
e2.printStackTrace();
}
Main.this.runOnUiThread(new Runnable() {
public void run() {
try {
stat.setText("نمیتونم وصل شم به "+"\n"+name+" : "+rele);
stat.setTextColor(Color.RED);
isc=false;
dialog.dismiss();
} catch (Exception e) {} }
});

dialog.dismiss();
}
}
}}).start();

mainb.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

try {
oc2();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
if(isc){
if(ison) {
mainb.setBackgroundResource(R.mipmap.offmain);
ison=false;
String data="#1234#"+"RELAY"+rele+"OFF";

send(data);
}else{
mainb.setBackgroundResource(R.mipmap.onmain);
ison=true;

String data="#1234#"+"RELAY"+rele+"ON";

send(data);
}
}
}});

}

@TargetApi(11)
private void in(){
Main.this.runOnUiThread(new Runnable() {
public void run() {
try {

ValueAnimator valueAnimator = ValueAnimator.ofFloat(0,0);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = (float) animation.getAnimatedValue();
event.setTranslationY(value);
delay.setTranslationY(value);
charger.setTranslationY(value);
daily.setTranslationY(value);
}
});

// 2 - Here set your favorite interpolator
valueAnimator.setInterpolator(new AccelerateInterpolator(1.5f));
valueAnimator.setDuration(1000);

// 3
valueAnimator.start();
} catch (Exception e) {} }
});
//
}
@TargetApi(11)
private void out(){

Main.this.runOnUiThread(new Runnable() {
public void run() {
try {
ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1000);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = (float) animation.getAnimatedValue();
event.setTranslationY(value);
delay.setTranslationY(value);
charger.setTranslationY(value);
daily.setTranslationY(value);
}
});

// 2 - Here set your favorite interpolator
valueAnimator.setInterpolator(new AccelerateInterpolator(1.5f));
valueAnimator.setDuration(1000);

// 3
valueAnimator.start();

//
} catch (Exception e) {} }
});
}
@TargetApi(11)
private void ffout(){

Main.this.runOnUiThread(new Runnable() {
public void run() {
try {
ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1000);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = (float) animation.getAnimatedValue();
event.setTranslationY(value);
delay.setTranslationY(value);
charger.setTranslationY(value);
daily.setTranslationY(value);
}
});

// 2 - Here set your favorite interpolator
valueAnimator.setInterpolator(new AccelerateInterpolator(1.5f));
valueAnimator.setDuration(10);

// 3
valueAnimator.start();

//
} catch (Exception e) {} }
});
}

@TargetApi(11)
private void spinX(){

Main.this.runOnUiThread(new Runnable() {
public void run() {
try {
ValueAnimator animator = ValueAnimator.ofFloat(0, 135);

animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

public void onAnimationUpdate(ValueAnimator animation) {
float value = (float) animation.getAnimatedValue();
// 2
hexa.setRotation(value);
}
});

animator.setInterpolator(new LinearInterpolator());
animator.setDuration(200);
animator.start();
} catch (Exception e) {

}
}});
}
@TargetApi(11)
private void spinP(){

Main.this.runOnUiThread(new Runnable() {
public void run() {
try {
ValueAnimator animator = ValueAnimator.ofFloat(0, -90);

animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

public void onAnimationUpdate(ValueAnimator animation) {
float value = (float) animation.getAnimatedValue();
// 2
hexa.setRotation(value);
}
});

animator.setInterpolator(new LinearInterpolator());
animator.setDuration(250);
animator.start();
} catch (Exception e) {

}
}});
}
public void send(String data){
try{

dos.writeByte(1);
dos.writeUTF(data);
dos.flush(); // Send off the data

}catch (IOException e){


}
}
private void oc2() throws IOException, InterruptedException {

if(Read2().contains("sndtrue")) {

if(!mp.isPlaying()) {
mp = MediaPlayer.create(this, R.drawable.oc2);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.start();
}
}
}
private void faild() throws IOException {

if(Read2().contains("sndtrue")) {
if(!mp.isPlaying()) {
mp = MediaPlayer.create(this, R.drawable.oc);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.start();
}
}
}

private void oc1() throws IOException {//faild
if(Read2().contains("sndtrue")) {
if(!mp.isPlaying()) {
mp = MediaPlayer.create(this, R.drawable.oc1);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.start();
}
}
}
public void ActiveRec(){
new Thread(new Runnable() {
public void run() {
try {
while(true) {

//==========================
Thread.sleep(200);
if ((line = dis.readLine()) != null) {

Main.this.runOnUiThread(new Runnable() {
public void run() {
if (line.equals("MineOFF")) {
mainb.setBackgroundResource(R.mipmap.offmain);
ison=false;
}
if (line.equals("MineON")) {
mainb.setBackgroundResource(R.mipmap.onmain);
ison=true;
}
}});
}
//==========================

}
} catch (final Exception e) {

}
}
}).start();
}
//=====================##########=====================
//=====================READ WRITE=====================
//=====================##########=====================
private void Write2(String data) {
try {
data=data.replace(" ","");
data=data.replace("\n","");
Context context = getApplicationContext();
if(path2==null)path2 = context.getFilesDir();
file2 = new File(path2, "Smart.txt");
FileOutputStream stream = new FileOutputStream(file2);
try {
stream.write(data.getBytes());
} finally {
stream.close();
}
}
catch (IOException e) {

}
}
private String Read2() throws IOException {

String ret = "";
Context context = getApplicationContext();
if(path2==null)path2 = context.getFilesDir();
file2 = new File(context.getFilesDir(), "Smart.txt");


int length = (int) file2.length();

byte[] bytes = new byte[length];

FileInputStream in = new FileInputStream(file2);
try {
in.read(bytes);
} catch (IOException e) {
// e.printStackTrace();
} finally {
in.close();
}

String contents = new String(bytes);
ret=contents;
return ret;
}


}

EJP EJP
Answer Source

You can't reconnect a TCP socket. You have to create a new one.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download