我正在使用TcpListener
使用C#开发服务器应用程序,该应用程序应该监听1000个GPS设备。当前代码正在与多个客户端连接,因此工作正常,但问题是一段时间后(可能是几小时或一天),侦听器将停止侦听客户端。有时,侦听器接受来自某些但不是全部设备的连接,有时它根本不接受任何连接。当我检查“资源监视器”时,有打开的连接并已接收数据,但新的连接未连接。
static void Main(string[] args)
{
try
{
MainAsync().Wait();
}
catch (Exception ex)
{ }
finally { }
}
static async Task MainAsync()
{
Console.WriteLine("Starting...");
var server = new TcpListener(IPAddress.Parse("IP Address"), “Port No”);
try
{
server.Start();
Console.WriteLine("Started.");
while (true)
{
var client = await server.AcceptTcpClientAsync().ConfigureAwait(false);
try
{
Console.WriteLine("-New Client Connected at: " + DateTime.Now.ToString());
var cw = new ClientWorking(client, true);
cw.ClientAsync().NoWarning();
}
catch (Exception ex)
{
client.Client.Close();
}
finally { }
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
class ClientWorking
{
TcpClient _client;
bool _ownsClient;
public ClientWorking(TcpClient client, bool ownsClient)
{
_client = client;
_ownsClient = ownsClient;
_client.ReceiveTimeout = 900000;
}
public async Task ClientAsync()
{
try
{
CSocketDB c = new CSocketDB();
while (_client.Client.Connected)
{
using (var stream = _client.GetStream())
{
using (var sr = new StreamReader(stream))
using (var sw = new StreamWriter(stream))
{
sw.FlushAsync().ConfigureAwait(false);
var data = default(string);
int i;
Byte[] bytes = new Byte[1024];
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = ByteArrayToString(bytes);
string[] dt0 = Regex.Split(data, "0d0a");
}
}
}
}
}
catch (Exception ex)
{
_client.Client.Close();
}
finally { }
}
}