Waypoint
Waypoint

Reputation: 17753

Android connect to server ip and port

what is the best approach of connecting android to server and ip and corresponding port? THis connection doesn't need to be all the time, but I am assuming I will send and recive files (in byte arrays or streams).

Thanks

Upvotes: 1

Views: 8525

Answers (1)

Squagem
Squagem

Reputation: 734

Since the Android Development Tools are native to Java, you can use simple Java Socket APIs to accomplish this goal (see ServerSocket and Socket).

Server Code

You must start by opening a ServerSocket on your host computer by defining a port to listen on:

ServerSocket ss = new ServerSocket([some_port]);

Then you must begin listening for a client by calling ss.accept(). This method will block until a client connects:

Socket my_socket = ss.accept();

You now have a socket on your server that you can manipulate as you wish (probably through the use of ObjectInputStream and ObjectOutputStream):

ObjectOutputStream out = new ObjectOutputStream(my_socket.getOutputStream());
ObjectInputStream in= new ObjectInputStream(my_socket.getInputStream());

Client Code

You must establish a connection with the server that you have just created. You will do this by initializing a socket and passing in the IP address of your server (usually localhost for most testing purposes) and the port number on which your server is currently listening:

Socket socket = new Socket("localhost", [some_port]);

Again, establish some streams for communication:

ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());

And there you have it! You can now easily communicate with a server from an Android device. It is much simpler than you would think.

Please note, however, that this architecture implements TCP, which is much slower than UDP and will not work for any type of fast-paced data intensive games, but should accomplish your goals given your description above.

Upvotes: 8

Related Questions