Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android devices connected with NSD, how to send messages using sockets (Client-Client)?

I've recently setup P2P communication within my app in a couple of devices with help from this guide: http://developer.android.com/training/connect-devices-wirelessly/nsd.html

So, now I can find other devices in my network thats running my app. Now I want to send messages between clients. Can be 1,2 or more clients but messages will only go to 1 client at a time, more like a PING request but with some text.

I've been reading about sockets and it seems to be the way to go (Will communicate with iOS devices also in the nearby future). But.. In all examples and tutorials I found there is a server in the group of clients that all messages go through. I just want to send a message from client - to - client.

Basically I want:

  1. list all devices/clients in my network running my app, DONE! (Is having IpAdress, port etc to all of them)
  2. click one client and send a ping/message

Any hints or examples to look at? Should all client devices have a "server" also?

Regards, Kristoffer

like image 642
korrekorre Avatar asked Apr 24 '14 15:04

korrekorre


1 Answers

So I figured it out at last.

I was studying sockets a little more in detail. ex:

http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html

and realized that I needed a server on all clients to get it to work properly. So now all clients have a ServerSocket listening for incoming connections and a separate client socket for sending messages to these "servers".

It all seems to work with connections to both android and iOS devices.

A couple of working examples using this sockets:

http://examples.javacodegeeks.com/android/core/socket-core/android-socket-example/

http://thinkandroid.wordpress.com/2010/03/27/incorporating-socket-programming-into-your-applications/

/ Kristoffer

like image 127
korrekorre Avatar answered Oct 17 '22 21:10

korrekorre