0

I'm try to writing an online game with a socket connection. So I use asynctask to make a socket connection.

SocketServer.java

public class SocketServer{

private MyCustomListener listener;

private String ip = "127.0.0.1";
private int port = 4444;

@SuppressWarnings("unused")
private Context context;
private SocketAsync socketAsync;
private String dataInput, username;

public SocketServer(Context context) {
    this.context = context;
}

public void setOnRecieveMsgListener(MyCustomListener listener) {
    this.listener = listener;
}

public void connect() {
    socketAsync = new SocketAsync();
    socketAsync.execute();
}

public void sentData(String x, String y, String z) {
    dataInput = null;
    JSONObject object = new JSONObject();
    // JSON Encode
    socketAsync.sentJSON(object);
}

private class SocketAsync extends AsyncTask<Void, Void, String> {

    private Socket socket;
    private PrintWriter printWriter;

    @Override
    protected String doInBackground(Void... params) {
        try {
            socket = new Socket(InetAddress.getByName(ip),port);
            OutputStreamWriter streamOut = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
            printWriter = new PrintWriter(streamOut);
            streamOut.flush();
            BufferedReader streamIn = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
            Looper.prepare();
            while(socket.isConnected()) {
                try {
                    dataInput = streamIn.readLine();
                    listener.onRecieveMessage(new MyListener(dataInput));
                }
                catch(Exception e) {}
            }
            Looper.loop();
        }
        catch(Exception e) {}
        return null;
    }

    public void sentJSON(JSONObject object) {
        if(socket.isConnected()) {
            try {
                printWriter.println(object.toString());
                printWriter.flush();
            }
            catch(Exception e) {}
        }
    }

}
}

Login.class

public class Login extends Activity implements MyCustomListener {

JSONObject object;
SocketServer socketserver;

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

    socketserver = new SocketServer(this);
    socketserver.setOnRecieveMsgListener(this);
    socketserver.connect();
    button();
}

private void button() {
    Button loginBt = (Button)findViewById(R.id.login_bt);
    final EditText un = (EditText)findViewById(R.id.username);
    final EditText ps = (EditText)findViewById(R.id.password);
    final String[] logindata = new String[2];

    loginBt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            logindata[0] = un.getText().toString();
            logindata[1] = ps.getText().toString();
            socketserver.setUsername(logindata[0]);
            socketserver.sentData("SERVER", "TEST", "login");
        }
    });
}

private void toMainScreen() {
    Intent x = new Intent(this,Main.class);
    startActivity(x);
}

@Override
public void onRecieveMessage(MyListener ml) {
    try {
        JSONObject json = new JSONObject(ml.getMsgStr());
        System.out.println(json.getString("content"));
        if(json.getString("content").equals("TRUE")) {
            toMainScreen();
        }
        else
            Toast.makeText(getApplicationContext(), "Login Fail", Toast.LENGTH_SHORT).show();
    } catch (JSONException e) {
        Log.e("## JSON DECODE", e.toString());
        e.printStackTrace();
    }
}
}

Main.class

public class Main extends Activity implements MyCustomListener {

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

    //do some thing
}

@Override
public void onRecieveMessage(MyListener ml) {
    System.out.println("MAIN : " + ml.getMsgStr());
}
}

so how can I pass object "socketserver" from login class to main class? or is there an other way to do something like this?

sorry for my poor english.

Tanggyxyz
  • 11
  • 2
  • easiest way is to make a generalize class for AsyncTask and call them wherever you required – Kunu Feb 17 '14 at 04:42
  • Please have a look at this http://stackoverflow.com/questions/3821423/background-task-progress-dialog-orientation-change-is-there-any-100-working/3821998#3821998 –  Feb 17 '14 at 04:44
  • after passing `socketserver` object to Main.class what do you want retrieve from that `socketserver` object? – Hamid Shatu Feb 17 '14 at 04:48
  • Kunu - but I have to wait for some message from server like chat message at all the time. how can i do this? user3110424 - thanks Hamid Shatu - I want to maintain a connection with server because the sever will sent message to me all the time. – Tanggyxyz Feb 17 '14 at 04:49

1 Answers1

0

You should not try to pass an instance of SocketServer around. One of it's properties is context which means you should not used it outside the original context it was created in (i.e. activity it was created in) or you'll have memory leaks.

Your SocketServer class needs IP and port. This is the kind of information that you should pass between activities and then use that to create another instance of your SocketServer class.

Szymon
  • 42,577
  • 16
  • 96
  • 114