Friday, March 31, 2017

Android client connecting to java server example

As a case study on how to use a VPS, I bought a VPS from Amazon LightSail, wrote a server in Java and a client in Android:

VPS:
  1. I selected the preconfigured Ubuntu option. It has no GUI, you have to do everything on the command line.
  2. I created a static IP. 
  3. In order to access it freely (ping etc.), go to networking tab, under firewall add “All TCP+UDP”
  4. On Ubuntu, I installed OpenJDK8:
    1. sudo apt-get update
    2. sudo apt-get install openjdk-8*
  5. I installed Putty to use as an SSH terminal
  6. I installed Filezilla for file transfers.
Server software:
  1. Wrote server in Java on my laptop and transferred the code to VPS via FileZilla.
  2. I used gson for object-JSON conversions. The latest gson jar file can be downloaded from here.
  3. I wrote a java build script in Ubuntu using nano.
    1. Note that if you write the script in Windows and transfer it to Ubuntu, it might not work because line endings in Windows and Linux are different.
    2. To make the file executable: chmod +x filename
  4. I built and run the server. I prepared a shell script and ran it like so: ./script.sh
  5. To make sure that server keeps running when I disconnect putty, I used nohup and disown
  6. Update 15.10.2017: To keep nodejs server running do the following: 
    1. nodejs index.js> stdout.txt 2> stderr.txt &
    2. Do not close putty by clicking the top right "x", type exit.
  7. To kill a process
    1. Note PID by running ps -ef (or better, pgrep <process name>)
    2. Kill process with sudo kill PID

Android client software:
  1. Wrote client in Android Studio.
  2. I used gson for object-JSON conversions.
  3. I had to use AsyncTask for connection, otherwise I get NetworkOnMainThreadException
The source code for java server and android client is on GitHub.

TODO:
  • Server: Handle multiple simultaneous connection requests

No comments: