Yes, you need to listen to a port all the time. The "trick" is: you need to listen the way spending zero CPU time. The thread should call a blocking method which puts the thread in a special wait state; it is switched off by the OS and never scheduled back to execution until a connection comes from the client side.
Now, what is that kind of call? I use
TcpListener.AcceptTcpClient()
. Essentially, on the listening side you need two separate threads: one listening to the incoming connections (in cycle: when a client is accepted, its remote socket is added to you container of connected client, then the listener listens again, over and over; another one reads/writes from/to a network stream with all the connections so implementing your application-level protocol over TCP (in case of chat, this protocol is very simple, still am application-level protocol). You will need to use proper inter-thread synchronization primitives to work with share data, which is the shared container of clients.
You will need to use
TcpClient
and
TcpListener
classes; they do work on the level of sockets as you do, but on a bit higher level of abstraction. Your performance will not suffer at all.
Please see my past solutions where I sketch this design:
Multple clients from same port Number[
^],
automatic updater triggered via server[
^].
What I describe is the server side, however, you don't have to have purely client-server architecture with single passive threads and multiple active clients. Sometimes you need
inversion of control,
http://en.wikipedia.org/wiki/Inversion_of_control[
^].
For better understanding, please read about
pull and
push technology, or
server push:
http://en.wikipedia.org/wiki/Client%E2%80%93server_model[
^],
http://en.wikipedia.org/wiki/Pull_technology[
^],
http://en.wikipedia.org/wiki/Push_technology[
^].
—SA