I hope to have enough details in this questions.
Overview: My task is to get data from a TCP stream and have the data display on a gui and also format the data and write it to a file. I can do all of the items individually but I am having a problem glueing it all together.
In my main I call my tcp_listener
MyTcpListener.start();
MyTcpListener constantly loops and reads data
public class MyTcpListener
{
//public string start(ref CQ.ConQueue init_concurrent_queue)
public static void start()
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
....
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
// !!! ADD DATA TO QUE HERE
Program.ConQueue
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
data.ToString();
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}
In the above section whenever I get new data I write it to the console. But what I need to do is enqueue it to a concurrent queue that my other class can dequeue it from and write a file.
How should I go about this? Should I create the object in my main and pass it by reference to my other threads / classes?
Or is there a way that I can instantiate the object multiple times but only a single queue is created internally in memory and all objects access it?
You should pass your queue into the object
public string start(CQ.ConQueue queue)
I'm not sure what that object is, but .NET comes with a threadsafe Queue, ConcurrentQueue
There is such a think as static variables, which only have one instance no matter how many instances of your class you create. Using them for your type of problem is undesirable, since that's not what their meant for, it hides the sharing of the queue between your object and absolutely prevents you from ever having more than one queue.
I notice, you're passing by ref this is not required. If you pass a reference type in C# effectively passes a pointer to the original object. Passing that by ref has a different, more complex meaning (you pass the pointer by reference), which i don't think is your intention.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With