HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Socket listener for chat client

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
chatlistenerclientforsocket

Problem

I'm working on chat client for mobile devices, and I need to get new messages from server as fast, as possible and, if it possible, keep battery alive.

I've created such class, that listens for server on it's own thread. Here is run method of Thread:

```
@Override
public void run(){
try{
//actually these lines defined in constructor
String address="127.0.0.1";
int port=46969;
int reconnectInterval=15000;
int interval=1000;
Socket socket;
//--- constructor's end

SocketAddress addr=new InetSocketAddress(address, port);
InputStream is=null;
OutputStream os=null;
ByteBuffer buf=ByteBuffer.allocate(2048);

int beat=0;
while(!interrupted()){
//if socket not created - create it
//if socket not connected - connect it
if(socket==null || !socket.isConnected()){
socket=new Socket();
while(!socket.isConnected()){
try{
socket.connect(addr,reconnectInterval);
}catch(IOException e){
Log.d("AppLog", "Can't connect to socket. Reconnecting...");
socket=new Socket(); //recreate socket (if connection failed)
sleep(reconnectInterval);
}
continue;
}
try{
is=socket.getInputStream(); //open socket streams
os=socket.getOutputStream();
}catch(IOException e){
Log.d("AppLog","Can't open socket streams - IOException");
interrupt();
break;
}
Log.d("AppLog", "Socket connected");
}

while(socket.isConnected()){
sleep(interval);

//send heart beats to socket to check connection
beat++;

Solution

I'm not sure about your first question - I've never programmed on a mobile device where power was an issue.

In answer to your second question, one of the options for sockets that is contained in the specification for TCP/IP is SO_KEEPALIVE. When this is set to true, the internal socket mechanism takes care of keeping the connection alive so that you don't have to worry about heart beats or anything like that. The Socket class has accessors for SO_KEEPALIVE.

Also, you need to seriously refactor this code and extract out the two meaningful parts into functions (one does the connecting, one the R/W). As it is the code is too long and complicated to be able to easily follow the logic.

Context

StackExchange Code Review Q#10365, answer score: 5

Revisions (0)

No revisions yet.