TcpClient - receives unasked messages, concept

  • Thread starter Thread starter Markus Freitag
  • Start date Start date
M

Markus Freitag

Guest
Hello,
I have a client that needs to respond to messages.
The message are XML structure.
It seems to work, the problem where I see it, I read the list and then it will be filled.
List<string> listMessages = new List<string>();

I need your expert knowledge.
Do I have to use a thread-safe list, if so, how?
BlockingCollection<string> bc = new BlockingCollection<string>()
How do I delete the entries?

STEP1
public void Execute()
{
MyTokenSource = new CancellationTokenSource();
MyToken = MyTokenSource.Token;
try
{
Task.Run(() =>
{
Workingloop(MyToken); // besser so verwenden
});



//STEP2
public async void Workingloop(CancellationToken token)
{
int value1 = 0;
int value2 = 0;
string value3 = "";
try
{
while (!token.IsCancellationRequested)
{
List<string> recList = await SocketClient.ReceiveSocket(SocketDataEchange, token);

if (recList != null && recList.Count == 1)
{
if (recList[0] == "ConnectionReset")
{
recList.Clear();
Stop();
Connect(IP, Port);
Execute();
}
else
{
if (recList[0].Length > 0 && recList[0].Substring(0, 1) != "<")
recList.Clear();
}
}


//STEP3
internal class SocketsSendReceive
{
byte[] Buffer = new byte[1000];
String ReceiveBuffer = string.Empty;
int SizeReceive = -1;
internal async Task<List<string>> ReceiveSocket(Socket sck, CancellationToken myToken)
{
return await Task.Run(() =>
{
List<string> listMessages = new List<string>();
while (SizeReceive != 0 && !myToken.IsCancellationRequested)
{
if (sck.Connected == false)
{
return null;
}

try
{
// Sync
SizeReceive = sck.Receive(Buffer, 0, Buffer.Length, SocketFlags.None);
}
catch (SocketException eS)
{
Log.Error($"Socket Exception {eS.Message}");

listMessages = new List<string>();

switch ((SocketError)eS.ErrorCode)
{
default:
listMessages.Add(((SocketError)eS.ErrorCode).ToString());
break;
}
return listMessages;
}
catch (Exception e1)
{
break;
}

ReceiveBuffer += Encoding.ASCII.GetString(Buffer, 0, SizeReceive).Replace('\r', ' ').Replace('\n', ' ');
int lengthFirstTag = ReceiveBuffer.IndexOf(">");
if (lengthFirstTag <= 0)
continue;
Best regards, Markus

Continue reading...
 
Back
Top