Best way to implement a socket listener in C #

I have already searched for the answers, but cannot find anything like it ...

I am new to C #. I need to create a C # program using WinForms. It basically has 2 components: a UI, and then I need a process that constantly listens on a TCP socket port. If something happened, I need to raise an event or something similar so that I can update the interface.

Question. What is the best way to implement a process that should be constantly monitored while the program is running?

And then, when I receive a message, how can I notify the user interface that it needs to be updated?

Thanks!

+6
c # winforms sockets
source share
4 answers

You can use TcpListener , which is waiting for incoming connections in another thread. Every time you get a new connection, create a new thread to handle it. Use Control.Invoke to update the user interface from a thread other than the UI. Here is a quick example:

 public MainForm() { InitializeComponents(); StartListener(); } private TcpListener _listener; private Thread _listenerThread; private void StartListener() { _listenerThread = new Thread(RunListener); _listenerThread.Start(); } private void RunListener() { _listener = new TcpListener(IPAddress.Any, 8080); _listener.Start(); while(true) { TcpClient client = _listener.AcceptTcpClient(); this.Invoke( new Action( () => { textBoxLog.Text += string.Format("\nNew connection from {0}", client.Client.RemoteEndPoint); } ));; ThreadPool.QueueUserWorkItem(ProcessClient, client); } } private void ProcessClient(object state) { TcpClient client = state as TcpClient; // Do something with client // ... } 
+8
source share

You can use the TcpListener class. Here is an example in the documentation.

+1
source share

At startup, you can create (create) a new thread that listens for new messages in an endless loop. After receiving the message, the thread can update some share (set a flag). Of course, you could make it more complicated if you used a synchronized queue to send messages. Or through WCF (although this seems redundant for your purposes).

+1
source share

This may not be the best way to do this, but it should work ...

You can run your TCP listener code in a new thread when the program starts ... This way, you listen to the TCP code when the user interface is disconnected from others. When something happens in the TCP stream, it will have to signal the user interface stream with some event or event queue.

Now, from the point of view of updating the WinForms object, when something is received, I believe that only the thread that created the WinForms control can update the controls. Therefore, you will have to consider this as well.

This is a problem that I struggled with before as well ... In my current project I am doing what I mentioned above ... however there is a bit of thread synchronization to make it work.

+1
source share

All Articles