Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: .NET Threading Network
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:
 
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 Wink | ;)
Posted 1-Jun-12 5:05am
Edited 1-Jun-12 5:11am
v2

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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
  Permalink  
v6
Comments
losmac at 1-Jun-12 10:46am
   
Very good answer, my 5!
SAKryukov at 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 at 1-Jun-12 11:02am
   
Величезне дякую ;-))
losmac at 1-Jun-12 11:51am
   
Sergey, you're amazing! So many languages you know.
Спасибо. Это хорошо иметь Teбe зa друга.
SAKryukov at 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
Oleksandr Kulchytskyi at 1-Jun-12 11:01am
   
Yep, that is an amazing and astonishing answer =))
Thanks a lot to you =) My 5 points to you!!!!
SAKryukov at 1-Jun-12 11:23am
   
You are very welcome.
Good luck, call back.
--SA
losmac at 1-Jun-12 11:51am
   
Greetings from Poland ;)
SoMad at 1-Jun-12 13:59pm
   
It is a good answer, but I don't think it is always the right one. In this case it depends on the frequency of which the client needs the data (the question only says "periodically"). If the client only needs the data once per day, I might go with polling and avoid problems with keeping persistent TCP connections.
 
Soren Madsen
SAKryukov at 1-Jun-12 15:01pm
   
Agree with you note. I certainly advised based on my understanding and experience on much more frequent exchange of events/data, and OP confirms that this is the case. However, your note is important for the settings where it's not the case.
Thank you very much.
--SA
Oleksandr Kulchytskyi at 1-Jun-12 14:15pm
   
Using word periodically, i mean that client needs the data in interval of 3 to 1 second.
SAKryukov at 1-Jun-12 15:03pm
   
That kind of timing actually perfectly justifies my advice, which is to be applied to periods from millisecond to minutes or maybe more.
--SA
SoMad at 1-Jun-12 15:30pm
   
Absolutely! In this case he should get slapped if he used polling :-)
You already got my 5.
 
Soren Madsen
SAKryukov at 1-Jun-12 15:36pm
   
Thank you again.
--SA

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

  Print Answers RSS
0 OriginalGriff 562
1 Sergey Alexandrovich Kryukov 484
2 Maciej Los 325
3 DamithSL 233
4 Mathew Soji 195
0 OriginalGriff 7,168
1 Sergey Alexandrovich Kryukov 6,377
2 DamithSL 5,461
3 Manas Bhardwaj 4,876
4 Maciej Los 4,450


Advertise | Privacy | Mobile
Web02 | 2.8.1411023.1 | Last Updated 1 Jun 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100