1

I want to create a "game server"- the server will be able to manage multiple games (clients), receive/send data from/to client apps and store it in a DB. Since I'm new to Android- I'm having a problem creating this basic server program.

What I already did: An android app for the game (client), the client has a registration page that sends the user details to the server (which I don't have yet) in JSON. My questions:

  1. I couldn't find any example of a server using Restful Webservice- all I found are client side's examples and not server's. Can you give me any code example of a server which receives and sends data using JSON from/to multiple clients? Or at least a good direction to start and build such server?
  2. Should I use Android Studio to build the server?

P.S. notice that my questions are about the server side and the connection between it to the clients (not about the connection between server to db).

Thanks.

Client:

public class JsonToServer {

String name, email, password;
Context registerActivityContext;


public JsonToServer(String nameString, String emailString, String passwordString, Context context) {
    this.name = nameString;
    this.email = emailString;
    this.password = passwordString;
    this.registerActivityContext = context;
    new SendPostRequest().execute();

}

public class SendPostRequest extends AsyncTask<String, Void, String> {

    protected void onPreExecute(){}

    protected String doInBackground(String... arg0) {

        try {
            Log.d("params123","before connecting");
            URL url = new URL(""); // SERVER path
            Log.d("params123","after connecting");
            JSONObject postDataParams = new JSONObject();
            Log.d("params123","json created");
            postDataParams.put("name", name);
            postDataParams.put("password", password);
            postDataParams.put("email", email);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));
            writer.flush();
            writer.close();
            os.close();
            int responseCode=conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {

                Log.d("params123","httpOK");
                BufferedReader in=new BufferedReader(new
                        InputStreamReader(
                        conn.getInputStream()));
                StringBuffer sb = new StringBuffer("");
                String line="";

                while((line = in.readLine()) != null) {

                    sb.append(line);
                    break;
                }

                in.close();
                return sb.toString();

            }
            else {
                return new String("false : "+responseCode);
            }
        }
        catch(Exception e){
            return new String("Exception: " + e.getMessage());
        }

    }

    @Override
    protected void onPostExecute(String result) {

        Toast.makeText(registerActivityContext, result,
                Toast.LENGTH_LONG).show();
    }



}

public String getPostDataString(JSONObject params) throws Exception {

    StringBuilder result = new StringBuilder();
    boolean first = true;

    Iterator<String> itr = params.keys();

    while(itr.hasNext()){

        String key= itr.next();
        Object value = params.get(key);

        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(key, "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(value.toString(), "UTF-8"));


    }
    return result.toString();
}

}

SHAI
  • 789
  • 3
  • 10
  • 43

1 Answers1

1

The best way to tackle this is by using the Volley library to communicate with the web server. As for the web server, you have a myriad of options for a web server. You can use Apache/Nginx and PHP, Nodejs and javascript, etc..

  1. Android studio is really only designed to write applications for android devices. You will want to use a different IDE/text editor to write the code for your web server. Any text editor will do. Personally, I prefer using the editor from atom.io, but that is totally up to you. Alternatives are Netbeans, PHP Storm, Brackets, etc... If you are using PHP, I would suggest looking into setting up a LAMP(linux, apache, mysql, php) or WAMP(windows alternative) server. If using javascript, look into setting up a nodejs server.
Kris Lefeber
  • 38
  • 1
  • 4
  • Thanks, I'm still a bit confused, I use NetBeans for the server but I still didn't find any good example/explanation for a webService that will read the income JSON from a client (like the one I attached). – SHAI Feb 03 '17 at 05:49
  • [Here](http://stackoverflow.com/questions/18866571/receive-json-post-with-php) is an example for PHP. This explains how to read json data sent to the web service using POST. If you are using a different language, just let me know. – Kris Lefeber Feb 03 '17 at 08:30
  • I'm using Java on NetBeans, using the Gson library. – SHAI Feb 03 '17 at 17:34
  • I'm not familiar with Java web services, but [here](http://www.javainstance.com/2016/12/creating-restful-web-services-with-json.html) might be a good place to start. – Kris Lefeber Feb 04 '17 at 01:18
  • Thanks I'l check it out, I opened a new question- being a bit more specific http://stackoverflow.com/questions/42034206/receiving-json-data-from-android-client-to-server-need-a-better-way – SHAI Feb 04 '17 at 01:30