I've got an android device paired with a barcode scanner. The device is setup that every time the scanner reads a barcode a broadcast Intent is used and my app catches the data, adds some information to it , opens a socket to a server and sends the data.
[BroadcastReceiver(Enabled = true)]
public class FingerScannerReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
using (TcpClient client = new TcpClient(ip, port))
{
NetworkStream stream = client.GetStream();
var b = Encoding.ASCII.GetBytes(decodedData);
stream.Write(b, 0, b.Length);
}
}
}
The app also has a TCP listener running on port 3333. The server retrieves the data and open a socket to port 3333 and sends information back.
The server's TcpListener code:
while (_isServerWorking)
{
using (var client = await _server.AcceptTcpClientAsync())
{
string data = "";
NetworkStream stream = client.GetStream();
byte[] bytes = new byte[32267];
int n;
while ((n = stream.Read(bytes, 0, bytes.Length)) > 0)
data += Encoding.ASCII.GetString(bytes, 0, n);
OnServerConnected(args);
}
}
This works fine usually but once or twice a day the device can't connect anymore, a connection refused socket error is returned. On the server side netstat says that there are quite a few sockets in CLOSE_WAIT state
TCP 172.17.0.85:58627 192.168.30.28:41682 CLOSE_WAIT
TCP 172.17.0.85:58627 192.168.30.28:41684 CLOSE_WAIT
TCP 172.17.0.85:58627 192.168.30.28:41686 CLOSE_WAIT
There are 187 errors total and I think the connection refused is returned because of this. I'd say the client and server sockets are both closed correctly, but there must be something wrong.
What is going wrong here? Should a socket connection in an intent be handled differently on android? Should I close the sockets differently or set some option?