9
9
10
10
public class SocketClient {
11
11
12
- public static final String TAG = " SocketClient" ;
13
- private static SocketClient socketClient = null ;
12
+ private static final String TAG = SocketClient . class . getSimpleName () ;
13
+ private static SocketClient socketClient ;
14
14
private Socket socket ;
15
15
private OutputStream outputStream ;
16
16
private InputStream inputStream ;
17
17
private boolean isConnected = false ;
18
18
19
- public static final int DEFAULT_READ_BUFFER_SIZE = 32 * 1024 ;
20
-
21
- private byte [] buffer = new byte [DEFAULT_READ_BUFFER_SIZE ];
22
-
23
19
private byte [] receivedData ;
24
20
25
21
private SocketClient () {
26
22
}
27
23
28
24
public void openConnection (String ip , int port ) throws IOException {
25
+ Log .v (TAG , "Connecting to " + ip + ":" + port );
29
26
socket = new Socket (ip , port );
30
27
outputStream = socket .getOutputStream ();
31
28
inputStream = socket .getInputStream ();
@@ -58,21 +55,23 @@ public synchronized void write(byte[] data) throws IOException {
58
55
public synchronized int read (int bytesToBeRead ) throws IOException {
59
56
int numBytesRead = 0 ;
60
57
int readNow ;
61
- Log .v (TAG , "To read : " + bytesToBeRead );
58
+ final long start = System .currentTimeMillis ();
59
+ Log .v (TAG , "Bytes to read : " + bytesToBeRead );
62
60
int bytesToBeReadTemp = bytesToBeRead ;
63
- receivedData = new byte [DEFAULT_READ_BUFFER_SIZE ];
61
+ receivedData = new byte [bytesToBeRead ];
64
62
while (numBytesRead < bytesToBeRead ) {
65
- readNow = inputStream .read (buffer , 0 , bytesToBeReadTemp );
63
+ final long start2 = System .currentTimeMillis ();
64
+ readNow = inputStream .read (receivedData , numBytesRead , bytesToBeReadTemp );
65
+ Log .v (TAG , "Bytes read: " + readNow + " in " + (System .currentTimeMillis () - start2 ) + " ms" );
66
66
if (readNow <= 0 ) {
67
67
Log .e (TAG , "Read Error: " + bytesToBeReadTemp );
68
68
return numBytesRead ;
69
69
} else {
70
- System .arraycopy (buffer , 0 , receivedData , numBytesRead , readNow );
71
70
numBytesRead += readNow ;
72
71
bytesToBeReadTemp -= readNow ;
73
72
}
74
73
}
75
- Log .v ("Bytes Read" , " " + numBytesRead );
74
+ Log .v (TAG , "Total bytes read: " + numBytesRead + " in " + ( System . currentTimeMillis () - start ) + " ms" );
76
75
return numBytesRead ;
77
76
}
78
77
@@ -89,7 +88,7 @@ public void closeConnection() {
89
88
isConnected = false ;
90
89
}
91
90
} catch (Exception e ) {
92
- e . printStackTrace ( );
91
+ Log . e ( TAG , "Error closing connection" , e );
93
92
}
94
93
}
95
94
}
0 commit comments