Android Development: Responding to a socket request

Warning: Worst Blog post written ever in history!

in my current project, a simple multiplayer game, I need to react on a connection request from another device. Currently both devices start their own service discovery. On one device I go to the list of found services and pick on. On the click the ServiceHelper will try to resolve the chosen device and if successful it will start communication sending a simple ‘gameplayrequest’ string.

the other device reacts to this with a OK response. This response is generated only when the user accepts the ‘invitation’. Ok and now some code 😉

try {
	this.server = new Socket();
	server.connect(new InetSocketAddress(location,this.port));
	this.sendRequest(new GameRequestResponseNotifier(GameRequestResponseNotifier.REQUEST_CONNECTION,null));
			
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

....

public void sendRequest(Notifier n) {
 ClientRequestThread ct = new ClientRequestThread(n,this);
 Thread t  = new Thread(ct);
 t.start();
}

..
public void run() {
  try {
    Socket server = instance.getServerConnection();
    PrintWriter writer = new PrintWriter(instance.server.getOutputStream(),true);
				
   writer.println(notifier.toString());
if(!(notifier instanceof OKNotifier)){
	BufferedReader reader = new BufferedReader(new InputStreamReader(server.getInputStream()));
	String data = reader.readLine();
	instance.notifyAll(data);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

These are some code snippets First we need to connect to the other device after we done that we need to send a response. This has to be done in a separate thread. The reason for this is that Android does not allow any heavy operations in the main thread. When we have notified the device that we are ok with the request the result is notified to all our listeners ( the view in this case )

And now the code to start resolving the chosen service

listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Object item = listView.getItemAtPosition((int) id);
				
				ServiceHelper.getInstance(null).addObserver((Observer) ListActivity.this);
				ServiceHelper.getInstance(null).resolveService(
						(NsdServiceInfo) item);
				Log.d(TAG, item.toString());
			}

		});

We get an instance of our service helper and subscribe ourselves to it

We start to resolve the service and logging which thing we clicked.

Now the update code in this activity

		if (data instanceof Notifier) {
			Notifier n = (Notifier) data;
			switch (n.toString()) {
			case Notifier.SERVICE_RESOLVE_SUCCESS:
				sendGameRequest();
				break;
			case Notifier.SERVICE_RESOLVE_FAILED:
				showUnabletoConnectToast();
				break;
			case GameRequestResponseNotifier.RESPONCE_CONNECTION_ALLOWED:
				Log.i(TAG,"Lets go to the next screen!");
			}
		}
	}

the update call first checks if the data that we receive is of the type notifier ( a class created by me to send data and some payload ). after we have resolved succesfully (see previous code snippet) we send a request to the server (first snippet) . The server will respond with an ok response ( or response_connection_allowed in this case ). We will log that for now but in the future this will cause a switch to another activity.

That’s it for now.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.