TCP socket concurrency
Posted: 04 May 2023 16:38
Dear,
I have a background worker in C# code which interacts with ProppFrexx with the TCP client.
Sometimes, I send a command en retrieve the data, but I get input from another command.
Is there something possible to combat this?
Hereby my proof of concept code;
I have a background worker in C# code which interacts with ProppFrexx with the TCP client.
Sometimes, I send a command en retrieve the data, but I get input from another command.
Is there something possible to combat this?
Hereby my proof of concept code;
Code: Select all
using System.Net;
using System.Net.Sockets;
using System.Text;
var serverIp = "192.168.1.112"; // Replace with your server's IP address
var serverPort = 8052; // Replace with your server's port number
var serverEndPoint = new IPEndPoint(IPAddress.Parse(serverIp), serverPort);
using var client = new TcpClient();
client.Connect(serverEndPoint);
void SendTCP(string msg)
{
var message = $"{msg}\r\n\r\n";
var data = Encoding.ASCII.GetBytes(message);
client.GetStream().Write(data, 0, data.Length);
}
string Receive()
{
byte[] buffer = new byte[1024];
int bytesRead = client.GetStream().Read(buffer, 0, buffer.Length);
string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
// Console.WriteLine("Server response: {0}", response);
return response;
}
void GetEntries()
{
while (true)
{
SendTCP("AUTHORIZATION password");
Receive();
SendTCP("PLS_CURRENT_GET_ENTRIES");
Receive();
}
}
void GetName()
{
while (true)
{
SendTCP("AUTHORIZATION password");
Receive();
SendTCP("PLS_CURRENT_NAME_GET");
var data = Receive();
Console.WriteLine($"current name: {data}");
}
}
// Create two threads
Thread thread1 = new Thread(new ThreadStart(GetEntries));
Thread thread2 = new Thread(new ThreadStart(GetName));
// Start the threads
thread1.Start();
thread2.Start();
// Wait for the threads to finish
thread1.Join();
thread2.Join();
// Close the connection
client.Close();