Click here to Skip to main content
15,881,380 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone.
I have some doubts about my realization.
I need to implement some simple TCP sender/receiver.
On client side , i created simple class , internal implementation of which contains
TcpClient, that client periodically connects to appropriate address in network and get some portion of data , after getting this data he performs some action on that.

On server side i had TcpListener and thread in which i periodically receive TcpClient, after getting client, it supposed to simulate some portion of data and send it back to client side.
Server code you can see below:

C#
public class SharerImp2 : IDisposable
	{
		TcpListener _listener = null;
		Thread _mainThread = null;
		CancellationTokenSource _cts = null;

		public SharerImp2(string ip, int port)
		{
			IPAddress address;
			if (!IPAddress.TryParse(ip, out address))
				throw new ArgumentNullException("ip");

			_listener = new TcpListener(new IPEndPoint(address, port));
		}

		public void Start()
		{
			_cts = new CancellationTokenSource();

			_mainThread = new Thread(new ThreadStart(StartInternal));
			_mainThread.Name = "Listener thread";
			_mainThread.IsBackground = true;
			_mainThread.Start();
		}

		private void StartInternal()
		{
			_listener.Start();

			while (true)
			{
				if (_cts.IsCancellationRequested)
					break;

				TcpClient client = _listener.AcceptTcpClient();

				using (NetworkStream netStream = client.GetStream())
				{
					byte[] data= Common.CaptureScreenWinForms.CaptureInBytesRepresentation();
					netStream.Write(data, 0, data.Length);
					netStream.Flush();
				}
			}

			_listener.Stop();
		}

                ...... some stop method needs to be implemented.

		public void Dispose()
		{
			if (!_cts.IsCancellationRequested)
			{
				_cts.Cancel();
				_cts.Dispose();
			}
		}
	}


So my question consist of next:
1) Is it reasonable ,to client, every time to establish connection to server and get some portion of data? Or it would be better to establish connection one-time and periodically check for data availability??

2) It would be better to on server side accepting client and sending portion of data in additional thread or ThreadPool ??

All your suggestions and ideas will be taken ;)
Posted
Updated 1-Jun-12 4:11am
v2

1 solution

1) Both variants are very bad. This is a custom networking application, so it gives you enough freedom to avoid this polling approach. You need to use push, not pull technology (please see: http://en.wikipedia.org/wiki/Pull_technology[^], http://en.wikipedia.org/wiki/Push_technology[^]). Polling approach cannot be effective in principle. Here is what you can do: server accepts any number of clients. You need to develop a two-way custom application-level protocol (http://en.wikipedia.org/wiki/Application_layer[^]) with data going from the server to a client when some new data in the field requested by a client becomes available. A server part should memorize the set of current clients. This is called "publisher/subscriber". A client should connect and remain connected. A connection itself can be treated as subscription, but your protocol can define how a client submits subscription detail or modifies it.

2) No. Both your current variant and your proposed variant are bad. It's a common fallacy to create some unpredictable number of threads in the service. Such service would be on mercy of the client behavior: they can easily overwhelm its resources and ultimately crash it. The number of threads should be constant or defined in the very beginning of the run time (by reading some persistent configuration, for example). Actually, a service needs only two network threads: one accepting new connections, and another one performing all the data exchange with all available clients. If your service host has many CPUs/cores, you can add more threads, a little more then a number of cores, and divide the data exchange work load between them. Thread pool is much better then a thread created per request (or anything similar), but fixed number of threads is the best, for this kind of applications.

For some related ideas, please see my past answer:
Multple clients from same port Number[^].

—SA
 
Share this answer
 
v6
Comments
Maciej Los 1-Jun-12 10:46am    
Very good answer, my 5!
Sergey Alexandrovich Kryukov 1-Jun-12 10:53am    
Dziękuję, Maciej.
(As OP is from Ukraine, he can understand it, as it sounds "дякую" in Ukrainian :-)
--SA
Oleksandr Kulchytskyi 1-Jun-12 11:02am    
Величезне дякую ;-))
Maciej Los 1-Jun-12 11:51am    
Sergey, you're amazing! So many languages you know.
Спасибо. Это хорошо иметь Teбe зa друга.
Sergey Alexandrovich Kryukov 1-Jun-12 15:33pm    
Not really.

Despite my life in USSR where so many people were Ukrainians (in Russia and beyond), I did not really know this language; and I even hardly understood the speech.
However, this year we started to view Ukrainian "Ukraine Got Talent" show through YouTube (search "Украина мае талант"), so I started to understand this language much better. It is very interesting: this language is much more Western compared to Russian (somewhat closer to Polish, even if you do not consider Western Ukrainian, in part the language of the former Poland territories) and much more Slavic then Russian at the same time (among Slavic languages, Russian is the most shifted to use of Ugric, Mongolian-Tatar, Turkic and other Eastern lexical ancestry).

I found that this show ("... Got Talent") is run in nearly all countries but is something special in Ukraine, so many performers from other countries prefer to present their talent in Ukraine instead of their own countries. Maybe this is because Ukrainian host, judges and public are very open, nice, supportive, welcome people with open heart. Even when the judges brutally criticize performers (which they often do), they do it with such humor, regret, warmth, gratitude, often the sympathy to some maybe ridiculous but good people, so most reasonable people are not frustrated too much.

I also was amazed that I could not feel tension between people using different languages (big part of Ukrainians speak Russian and considerable part of population speak some funny dialects not perceived as Ukrainian or Russian but based on Russian (maybe I'm just not familiar with other dialects)); people are talking the language more convenient to them without hesitation and understand both, and some, notably the hostess, brilliantly switch from one language to another, depending on who is coming into the dialog... Interesting and very pleasant...

--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900