- Какие параметры влияют на производительность приложений? Часть 1. TCP Window Size
- Calculated window size in Wireshark
- 1 Answer 1
- Calculating optimal window size
- 2 Answers 2
- Not the answer you’re looking for? Browse other questions tagged tcp networking or ask your own question.
- Related
- Hot Network Questions
- Subscribe to RSS
- Setting window size on desktop for a Windows 10 UWP app
- 3 Answers 3
- Windows calculate window size
Какие параметры влияют на производительность приложений? Часть 1. TCP Window Size
Самый простой способ понять значение термина размер TCP окна (TCP Window Size), это представить разговор двух человек. Один человек говорит, а второй кивает головой или говорит да, тем самым подтверждая, что он понял, а по сути, получил все слова, которые ему были сказаны. После этого разговор продолжается. Если мы встречаем особо говорливого человека, то наша голова быстро загружается, и мы начинаем терять нить разговора или переспрашивать нашего собеседника. Тоже самое происходит и в Матрице — в мире цифр и машин.
Размер TCP окна (TCP Window Size) – количество октетов (начиная с номера подтверждения), которое принимающая сторона готова принять в настоящий момент без подтверждения. На стадии установления соединения рабочая станция и сервер обмениваются значениями максимального размера TCP окна (TCP Window Size), которые присутствуют в пакете и эти значения можно легко увидеть, воспользовавшись захватом трафика.
Например, если размер окна получателя равен 16384 байта, то отправитель может отправить 16384 байта без остановки. Принимая во внимание, что максимальная длина сегмента (MSS) может быть 1460 байт, то отправитель сможет передать данный объем в 12 фреймах, и затем будет ждать подтверждение доставки от получателя и информации по обновлению размера окна. Если процесс прошел без ошибок, то размер окна может быть увеличен. Таким образом, реализуется размер скользящего окна в стеке протокола TCP.
В зависимости от состояния каналов связи, размер окна может быть больше или меньше. Каналы связи могут быть высокоскоростными (большая пропускная способность) и протяженными (большая задержка и возможно потери), поэтому при небольшом размере TCP окна мы будем вынуждены отправлять один или несколько фреймов и ждать подтверждения от получателя, затем процесс повторяется. Таким образом, наши приложения будут неэффективно использовать доступную полосу пропускания. Пакетов будет много, но реального полезного трафика будет передано не много. Чтобы получить максимальную пропускную способность, необходимо использовать оптимально установленный размер передающего и принимающего окна для канала, который вы используете.
Для расчёта максимального размера окна (т.е. максимальный объем данных, которые могут передаваться одним пользователем другому в канале связи) рассчитывается по формуле:
Полоса пропускания (бит/сек) * RTT (круговое время передачи по сети) = размер окна в битах
Таким образом, если ваши два офиса соединяет канал связи в 10 Мбит/сек и круговое время составляет 85 миллисекунд, то воспользовавшись данной формулой, мы получим значение окна равное:
10 000 000 * 0,085 / 8 = 106250 байт
Размер поля Window в заголовке TCP составляет 16 бит; это означает, что узел TCP может указать максимальный размер TCP окна 65535 байт. Таким образом, максимальная пропускная способность составляет:
65535 * 8 / 0,085 = 6,2 Мбит/сек
т.е. чуть больше 50% от реально доступной полосы пропускания канала.
В современных версиях операционных систем можно увеличить размер окна TCP Window Size и включить динамическое изменение окна в зависимости от состояния канала связи. В предложении RFC 1323 дано определение масштабирования окон, позволяющего получателю указывать размер окна больше 65535 байт, что позволит применять большие размеры окон и высокоскоростные каналы передачи. Параметр TCP Window Scale указывает коэффициент масштабирования окна, который в сочетании с 16-битным полем Window в заголовке TCP может увеличивать размер окна приема до максимального значения, составляющего примерно 1 ГБ. Параметр Window Scale отправляется только в сегментах синхронизации (SYN) при установке соединения. На нашем скриншоте из WireShark он составляет 256. Устройства, общающиеся друг с другом, могут указывать разные коэффициенты масштабирования для TCP окон.
Таким образом, активировав масштабирование окон TCP и уменьшив круговое время передачи по сети, мы сможем повысить эффективность использования доступной полосы пропускания и как следствие скорость работы приложений. А проверить это можно захватив пакеты, и посмотреть о каких значениях размера окна и коэффициенте масштабирования договорились устройства в момент установки соединения. Это динамическое увеличение и уменьшение размера окна является непрерывным процессом в TCP и определяет оптимальный размер окна для каждого сеанса. В очень эффективных сетях размеры окна могут стать очень большими, потому что данные не теряются. В сетях, где сетевая инфраструктура перегружена, размер окна, вероятно, останется маленьким.
Calculated window size in Wireshark
I see that the calculated window size is set to 5888 with the three handshake, however it jumps to 7808 with the first ACK. Can someone explain me why and what algorithm Linux (Linux OS and Wireshark) used to calculate this window?
I understand window scaling concept and I don’t have any congestion or slow start at this point of time. 5888 was SYN. 2000 in flight after two seg push. So you have 3888 available now. At this point you send ACK 1001, so the receiver shoots out ACK with updated window size (3888+1000=4888). But I see 7808! How? I observe such increase for every ack, unable to quantitatively reason this out.
1 Answer 1
This post has a good explanation for what you’re seeing.
What you see is normal behavior. Both sides send a small window size and neither announce that they are able to use window scaling. So in the next step they both pull up their TCP window to 64k to allow the other node to send more than just a few packets in case that there is a lot of data to be transferred.
It’s quite normal to see that kind of session behavior — as soon as both know that the connection is established and what the parameters are they simply adjust their window.
It is to conserve memory for connection that are not guaranteed to be established yet. The OS/TCP stack needs to reserve as much memory for incoming bytes as promised in the window size (which is essentially just a buffer), so if you waste too much memory on connections from the start you might run out of memory.
Calculating optimal window size
I’m currently trying to calculate the optimal window size. I got these variables:
- Propagation delay: 10 ms
- Bit speed: 100 kbps
- Frame size: 20 bytes
When the propagation delay is 10 ms we get a limit when the window size is 13 and when the propagation delay is 20 ms we get a limit when we have a window size of 24.
Is there any formula to calculate the maximum window size?
2 Answers 2
The formula to your Question is:
Where: Bitspeed = 100 in your case 2*tp = RTT (The time it takes to send and return a package), which in your case is 20 And buffer = 20, 20*8 to get the bitsize Windowsize = the thing you want calculated
Hope I was helpful!
Bandwidth times delay. It’s called the bandwidth-delay product.
Not the answer you’re looking for? Browse other questions tagged tcp networking or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Setting window size on desktop for a Windows 10 UWP app
I’ve just started learning UWP app development on Windows 10 Pro using Visual Studio 2015 Community Edition. I tried to modify the C# version of the official «Hello, World!» sample by setting the Width and Height attributes of the Page tag in MainPage.xaml.
Interestingly, when I start the app, its size will be different. Moreover, if I resize its window and then restart it, the app seems to remember its previous window size.
Is it possible to force a UWP app to have a predefined window size, at least on desktop PCs?
3 Answers 3
Try setting PreferredLaunchViewSize in your MainPage ‘s constructor like this:
As @kol also pointed out, if you want any size smaller than the default 500×320, you will need to manually reset it:
You don’t really have control over the window size, and even if you will try to re-size it it may fail. I’ve asked the same question on MSDN forums and got the answer here:
BTW, here is the solution in your event handler «OnLaunched» or in your Event Handler «OnActivated» find:
And replace it with:
It is better if you place this code into the «OnActivated()» event handler as it will set your defined size when the app starts and when it becomes active after any interruptions.
In the «desiredSize» calculation, 800 is the width and 600 is the height. This calculation is needed, because the size is in DPI, so you have to convert it from pixels to DPI.
Also keep in mind that size cannot be smaller than «320×200».
Windows calculate window size
» means nesting-related): — Failed at: @displayUserCertifications user_id [in template «custom.author-acclaim-certifications» at line 4, column 9] ——>
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Email to a Friend
- Report Inappropriate Content
I captured some TCP comunication because there is a issue with long respons of some application.
I see in some TCP packets using Wireshark:
window size value:593
Can this values indicate some issue?
Or is it correct?
I have other capture when respons of application is OK and there is still the same value «window size value» and «Calculated window size»
» means nesting-related): — Failed at: @displayUserCertifications user_id [in template «custom.author-acclaim-certifications» at line 4, column 9] ——>
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Email to a Friend
- Report Inappropriate Content
The Author of this posting offers the information contained within this posting without consideration and with the reader’s understanding that there’s no implied or expressed suitability or fitness for any purpose. Information provided is for informational purposes only and should not be construed as rendering professional advice of any kind. Usage of this posting’s information is solely at reader’s own risk.
In no event shall Author be liable for any damages whatsoever (including, without limitation, damages for loss of use, data or profit) arising out of the use or inability to use the posting’s information even if Author has been advised of the possibility of such damage.
Window size is only two bytes, so it cannot be larger than 64KB. To allow larger receive windows, another byte (I think actually 7 bits) were made an option to «scale» window size by some power of two. So if scale «says» multiply 64KB by 4, actual window size is 256KB.
Windows scaling is an option of later TCP. Older TCP stacks don’t support it, and if they don’t, they revert to using window size as is.