I have an application in which I need to create a socket connection. My requirement is: once my socket connection is established it needs to be alive until I personally close it. And every 3 minutes I have to send data packets to the other end. Can anyone provide me some code samples that will help me to do this?
A socket is an endpoint for communication between two machines. The actual work of the socket is performed by an instance of the SocketImpl class. An application, by changing the socket factory that creates the socket implementation, can configure itself to create sockets appropriate to the local firewall.
A socket is a communications connection point (endpoint) that you can name and address in a network. Socket programming shows how to use socket APIs to establish communication links between remote and local processes.
If you need to determine the current state of the connection, make a nonblocking, zero-byte Send call. If the call returns successfully or throws a WAEWOULDBLOCK error code (10035), then the socket is still connected; otherwise, the socket is no longer connected.
Listening on events Like I mentioned earlier, Socket.IO is bidirectional, which means we can send events to the server, but also at any time during the communication the server can send events to us. We then can make the socket listen an event on onCreate lifecycle callback.
Socket connections in Android are the same as in Java: http://www.oracle.com/technetwork/java/socket-140484.html
Things you need to be aware of:
Take a look at AlarmManager
, if you need scheduled execution of your code.
Do you need to run your code and receive data even if user does not use the app any more (i.e. app is inactive)?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With