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 😉

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

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

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 Reply

Your email address will not be published. Required fields are marked *

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