<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Erdem Bilgin on Medium]]></title>
        <description><![CDATA[Stories by Erdem Bilgin on Medium]]></description>
        <link>https://medium.com/@bilginerdem?source=rss-115a055e157a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vG7KpyvZFkKD0i-Tg_NOXg@2x.jpeg</url>
            <title>Stories by Erdem Bilgin on Medium</title>
            <link>https://medium.com/@bilginerdem?source=rss-115a055e157a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 15:33:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bilginerdem/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Compression, BigEndian and LittleEndian, Bits]]></title>
            <link>https://medium.com/codex/compression-bigendian-and-littleendian-bits-33701cdfb121?source=rss-115a055e157a------2</link>
            <guid isPermaLink="false">https://medium.com/p/33701cdfb121</guid>
            <category><![CDATA[compression]]></category>
            <category><![CDATA[big-endian]]></category>
            <category><![CDATA[little-endian]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[cpp]]></category>
            <dc:creator><![CDATA[Erdem Bilgin]]></dc:creator>
            <pubDate>Sat, 26 Oct 2024 09:19:30 GMT</pubDate>
            <atom:updated>2024-10-29T17:04:31.833Z</atom:updated>
            <content:encoded><![CDATA[<p>In Programming, you can come across a definition called big-endian and little-endian. Today we will talk about these definitions and using with compressing.</p><p>Completly, It will custom compression algorithm. Cannot be use in general process but, maybe you can use this algorithm in your process such as socket package, log file.</p><p>Now, let’s talk about the definitions of little-endian and big-endian. Little-endian and big-endian are related to data storage formats and refer to how the bytes of a number are organised in memory or communication. These concepts are often important in low-level programming, networking and data protocols.</p><figure><img alt="Compression, BigEndian and LittleEndian, Bits by generated AI" src="https://cdn-images-1.medium.com/max/1024/1*FiXZte2yQyWU2rh9QN6FNw.jpeg" /><figcaption>Compression, BigEndian and LittleEndian, Bits</figcaption></figure><p>In a <strong>little-endian</strong> system, the least significant byte of a multi-byte value (the least significant byte) is stored first in memory. For example, 0x12345678, a 4-byte number, is stored in memory as follows:</p><pre>78 56 34 12</pre><p>This method is common on many modern hardware, such as Intel processors. The advantage of <strong>little-endian</strong> is that it is faster when accessing small bytes because the smallest byte is located at the beginning of memory.</p><p>In a <strong>big-endian</strong> system, the byte with the highest value (the most significant byte) of a multi-byte value is stored first in memory. The same number 0x12345678 is stored as follows in big-endian system:</p><pre>12 34 56 78</pre><p>The <strong>big-endian</strong> scheme is sometimes preferred because it is closer to the human way of reading numbers and is common in networking protocols. For example, the TCP/IP protocol uses a big-endian format.</p><p>The difference between these two orders is important when transferring data or storing data in memory. For example, when you send data from one system to another, if the systems use different <strong>endian</strong>, you may need to perform a conversion to interpret the data correctly.</p><p><strong>What is the relationship between compression and these definitions?</strong></p><p>To understand the relationship, it is necessary to discuss the Low and High bit.</p><p>- <strong>Low and High bits</strong> means dividing the bits of a number into smaller parts.</p><p>- <strong>Low bits</strong>: Refers to the lowest valued bits of a number (for example, the lowest 16 bits of a u32 number).</p><p>- <strong>High bits</strong>: Refers to the highest-valued bits of the same number (for example, the highest 16 bits of a u32 number).</p><p>For example, the low and high bits of the 32-bit number 0x12345678 can be broken down as follows:</p><p>- <strong>High bits</strong>: 0x1234</p><p>- <strong>Low bits</strong>: 0x5678</p><p>- <strong>Endianness (Little-endian/Big-endian)</strong> defines the order in which data is stored in memory or during communication. This is especially important when transferring data between different computer architectures and network protocols.</p><p>- <strong>Low and High bits</strong> are the way we break down and process the data. It is used to perform a specific operation by taking the lowest and highest bits of the number separately or to reduce data loss during compression.</p><p>The two are different concepts, but they may need to be considered together when storing and transferring data, because the ordering of data in memory depends on endianness and this can affect low/high bit based operations.</p><p><strong>Now let’s do compression with a simple example.</strong></p><pre>//Let&#39;s make a simple StockPrice struct.<br>struct StockPrice {<br>    double price;<br>    uint64_t volume; <br>};</pre><p><strong>Step 1: Simple Compression</strong></p><p>In this step we use a simple method that compresses and decompresses the StockPrice structure:</p><pre>std::vector&lt;uint8_t&gt; compressStockPriceSimple(const StockPrice&amp; stock) {<br>    std::vector&lt;uint8_t&gt; buffer;<br><br>    // Store the price as a double (8 bytes)<br>    uint64_t price_bits = *reinterpret_cast&lt;const uint64_t*&gt;(&amp;stock.price);<br>    for (int i = 0; i &lt; 8; ++i) {<br>        buffer.push_back(price_bits &amp; 0xFF);<br>        price_bits &gt;&gt;= 8;<br>    }<br><br>    // Store the volume as a uint64_t (8 bytes)<br>    uint64_t volume = stock.volume;<br>    for (int i = 0; i &lt; 8; ++i) {<br>        buffer.push_back(volume &amp; 0xFF);<br>        volume &gt;&gt;= 8;<br>    }<br><br>    return buffer;<br>}<br><br>StockPrice decompressStockPriceSimple(const std::vector&lt;uint8_t&gt;&amp; data) {<br>    size_t index = 0;<br><br>    // Read the price as a double<br>    uint64_t price_bits = 0;<br>    for (int i = 0; i &lt; 8; ++i) {<br>        price_bits |= static_cast&lt;uint64_t&gt;(data[index++]) &lt;&lt; (8 * i);<br>    }<br>    double price = *reinterpret_cast&lt;double*&gt;(&amp;price_bits);<br><br>    // Read the volume as a uint64_t<br>    uint64_t volume = 0;<br>    for (int i = 0; i &lt; 8; ++i) {<br>        volume |= static_cast&lt;uint64_t&gt;(data[index++]) &lt;&lt; (8 * i);<br>    }<br><br>    return {price, volume};<br>}</pre><p><strong>2. Improving Compression (Using u8, u16, u32)</strong></p><p>In this step, we ensure that the data is stored as u8, u16 or u32 according to its value. For larger data, we continue as u64.</p><pre>std::vector&lt;uint8_t&gt; compressStockPriceOptimized(const StockPrice&amp; stock) {<br>    std::vector&lt;uint8_t&gt; buffer;<br><br>    // Compress price<br>    if (stock.price &lt; 256.0) {<br>        buffer.push_back(0b00); // 00 -&gt; stored as u8<br>        buffer.push_back(static_cast&lt;uint8_t&gt;(stock.price));<br>    } else if (stock.price &lt; 65536.0) {<br>        buffer.push_back(0b01); // 01 -&gt; stored as u16<br>        uint16_t price_u16 = static_cast&lt;uint16_t&gt;(stock.price);<br>        buffer.push_back(price_u16 &amp; 0xFF);<br>        buffer.push_back(price_u16 &gt;&gt; 8);<br>    } else {<br>        buffer.push_back(0b10); // 10 -&gt; stored as u32<br>        uint32_t scaled_price = static_cast&lt;uint32_t&gt;(stock.price * 100.0);<br>        for (int i = 0; i &lt; 4; ++i) {<br>            buffer.push_back(scaled_price &amp; 0xFF);<br>            scaled_price &gt;&gt;= 8;<br>        }<br>    }<br><br>    // Compress volume (same logic)<br>    if (stock.volume &lt; 256) {<br>        buffer.push_back(0b00); // 00 -&gt; stored as u8<br>        buffer.push_back(static_cast&lt;uint8_t&gt;(stock.volume));<br>    } else if (stock.volume &lt; 65536) {<br>        buffer.push_back(0b01); // 01 -&gt; stored as u16<br>        uint16_t volume_u16 = static_cast&lt;uint16_t&gt;(stock.volume);<br>        buffer.push_back(volume_u16 &amp; 0xFF);<br>        buffer.push_back(volume_u16 &gt;&gt; 8);<br>    } else {<br>        buffer.push_back(0b10); // 10 -&gt; stored as u32<br>        uint32_t volume_u32 = static_cast&lt;uint32_t&gt;(stock.volume);<br>        for (int i = 0; i &lt; 4; ++i) {<br>            buffer.push_back(volume_u32 &amp; 0xFF);<br>            volume_u32 &gt;&gt;= 8;<br>        }<br>    }<br><br>    return buffer;<br>}<br><br>StockPrice decompressStockPriceOptimized(const std::vector&lt;uint8_t&gt;&amp; data) {<br>    size_t index = 0;<br><br>    // Decompress price<br>    uint8_t price_type = data[index++];<br>    double price = 0.0;<br><br>    switch (price_type) {<br>        case 0b00:<br>            price = static_cast&lt;double&gt;(data[index++]);<br>            break;<br>        case 0b01: {<br>            uint16_t price_u16 = data[index++] | (data[index++] &lt;&lt; 8);<br>            price = static_cast&lt;double&gt;(price_u16);<br>            break;<br>        }<br>        case 0b10: {<br>            uint32_t scaled_price = 0;<br>            for (int i = 0; i &lt; 4; ++i) {<br>                scaled_price |= static_cast&lt;uint32_t&gt;(data[index++]) &lt;&lt; (8 * i);<br>            }<br>            price = static_cast&lt;double&gt;(scaled_price) / 100.0;<br>            break;<br>        }<br>    }<br><br>    // Decompress volume (same logic)<br>    uint8_t volume_type = data[index++];<br>    uint64_t volume = 0;<br><br>    switch (volume_type) {<br>        case 0b00:<br>            volume = data[index++];<br>            break;<br>        case 0b01:<br>            volume = data[index++] | (data[index++] &lt;&lt; 8);<br>            break;<br>        case 0b10: {<br>            uint32_t volume_u32 = 0;<br>            for (int i = 0; i &lt; 4; ++i) {<br>                volume_u32 |= static_cast&lt;uint32_t&gt;(data[index++]) &lt;&lt; (8 * i);<br>            }<br>            volume = volume_u32;<br>            break;<br>        }<br>    }<br><br>    return {price, volume};<br>}</pre><ul><li>price and volume are stored as u8 or u16 for small values.</li><li>For large values they are stored as u32.</li><li>Compression reduces the data size and makes efficient use of memory.</li></ul><p><strong>3. Using Low and High Bits</strong></p><p>In this step, we further optimise the compression by splitting the u32 values into 16-bit high and low bits.</p><pre>#include &lt;iostream&gt;<br>#include &lt;vector&gt;<br>#include &lt;cstdint&gt;<br>#include &lt;cmath&gt;<br><br>struct StockPrice {<br>    double price;<br>    uint64_t volume;<br>};<br><br>std::vector&lt;uint8_t&gt; compressStockPriceWithBits(const StockPrice&amp; stock) {<br>    std::vector&lt;uint8_t&gt; buffer;<br><br>    // Compress price<br>    if (stock.price &lt; 256.0) {<br>        buffer.push_back(0b00); // 00 -&gt; stored as u8<br>        buffer.push_back(static_cast&lt;uint8_t&gt;(stock.price));<br>    } else if (stock.price &lt; 65536.0) {<br>        buffer.push_back(0b01); // 01 -&gt; stored as u16<br>        uint16_t price_u16 = static_cast&lt;uint16_t&gt;(stock.price);<br>        buffer.push_back(price_u16 &amp; 0xFF);<br>        buffer.push_back(price_u16 &gt;&gt; 8);<br>    } else {<br>        uint32_t scaled_price = static_cast&lt;uint32_t&gt;(stock.price * 100.0);<br>        uint16_t high_bits = scaled_price &gt;&gt; 16;<br>        uint16_t low_bits = scaled_price &amp; 0xFFFF;<br><br>        if (high_bits == 0) {<br>            buffer.push_back(0b10); // 10 -&gt; low bits only<br>            buffer.push_back(low_bits &amp; 0xFF);<br>            buffer.push_back(low_bits &gt;&gt; 8);<br>        } else {<br>            buffer.push_back(0b11); // 11 -&gt; high and low bits<br>            buffer.push_back(high_bits &amp; 0xFF);<br>            buffer.push_back(high_bits &gt;&gt; 8);<br>            buffer.push_back(low_bits &amp; 0xFF);<br>            buffer.push_back(low_bits &gt;&gt; 8);<br>        }<br>    }<br><br>    // Compress volume (similar logic)<br>    if (stock.volume &lt; 256) {<br>        buffer.push_back(0b00); // 00 -&gt; stored as u8<br>        buffer.push_back(static_cast&lt;uint8_t&gt;(stock.volume));<br>    } else if (stock.volume &lt; 65536) {<br>        buffer.push_back(0b01); // 01 -&gt; stored as u16<br>        uint16_t volume_u16 = static_cast&lt;uint16_t&gt;(stock.volume);<br>        buffer.push_back(volume_u16 &amp; 0xFF);<br>        buffer.push_back(volume_u16 &gt;&gt; 8);<br>    } else {<br>        uint32_t volume_u32 = static_cast&lt;uint32_t&gt;(stock.volume);<br>        uint16_t high_bits = volume_u32 &gt;&gt; 16;<br>        uint16_t low_bits = volume_u32 &amp; 0xFFFF;<br><br>        if (high_bits == 0) {<br>            buffer.push_back(0b10); // Low bits only<br>            buffer.push_back(low_bits &amp; 0xFF);<br>            buffer.push_back(low_bits &gt;&gt; 8);<br>        } else {<br>            buffer.push_back(0b11); // High and low bits<br>            buffer.push_back(high_bits &amp; 0xFF);<br>            buffer.push_back(high_bits &gt;&gt; 8);<br>            buffer.push_back(low_bits &amp; 0xFF);<br>            buffer.push_back(low_bits &gt;&gt; 8);<br>        }<br>    }<br><br>    return buffer;<br>}<br><br>StockPrice decompressStockPriceWithBits(const std::vector&lt;uint8_t&gt;&amp; data) {<br>    size_t index = 0;<br><br>    // Decompress price<br>    uint8_t price_type = data[index++];<br>    double price = 0.0;<br><br>    switch (price_type) {<br>        case 0b00:<br>            price = static_cast&lt;double&gt;(data[index++]);<br>            break;<br>        case 0b01: {<br>            uint16_t price_u16 = data[index++] | (data[index++] &lt;&lt; 8);<br>            price = static_cast&lt;double&gt;(price_u16);<br>            break;<br>        }<br>        case 0b10: {<br>            uint16_t low_bits = data[index++] | (data[index++] &lt;&lt; 8);<br>            price = static_cast&lt;double&gt;(low_bits) / 100.0;<br>            break;<br>        }<br>        case 0b11: {<br>            uint16_t high_bits = data[index++] | (data[index++] &lt;&lt; 8);<br>            uint16_t low_bits = data[index++] | (data[index++] &lt;&lt; 8);<br>            uint32_t scaled_price = (static_cast&lt;uint32_t&gt;(high_bits) &lt;&lt; 16) | low_bits;<br>            price = static_cast&lt;double&gt;(scaled_price) / 100.0;<br>            break;<br>        }<br>    }<br><br>    // Decompress volume (similar logic)<br>    uint8_t volume_type = data[index++];<br>    uint64_t volume = 0;<br><br>    switch (volume_type) {<br>        case 0b00:<br>            volume = data[index++];<br>            break;<br>        case 0b01:<br>            volume = data[index++] | (data[index++] &lt;&lt; 8);<br>            break;<br>        case 0b10: {<br>            uint16_t low_bits = data[index++] | (data[index++] &lt;&lt; 8);<br>            volume = static_cast&lt;uint64_t&gt;(low_bits);<br>            break;<br>        }<br>        case 0b11: {<br>            uint16_t high_bits = data[index++] | (data[index++] &lt;&lt; 8);<br>            uint16_t low_bits = data[index++] | (data[index++] &lt;&lt; 8);<br>            volume = (static_cast&lt;uint64_t&gt;(high_bits) &lt;&lt; 16) | low_bits;<br>            break;<br>        }<br>    }<br><br>    return {price, volume};<br>}</pre><ul><li>If the price and volume values fit in u32, they are stored more efficiently over the high and low bits.</li><li>This method also compresses large values into smaller chunks.</li></ul><p>I hope it has been an explanatory and useful article on Little-endian, Bit-endian and Bits.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33701cdfb121" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/compression-bigendian-and-littleendian-bits-33701cdfb121">Compression, BigEndian and LittleEndian, Bits</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write from simple to advanced socket programming with Rust (Part IV)]]></title>
            <link>https://medium.com/codex/advanced-socket-programming-with-rust-part-iv-bonus-trick-bdcf24658b73?source=rss-115a055e157a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdcf24658b73</guid>
            <category><![CDATA[socket-programming]]></category>
            <category><![CDATA[compress]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[Erdem Bilgin]]></dc:creator>
            <pubDate>Thu, 22 Aug 2024 17:11:22 GMT</pubDate>
            <atom:updated>2024-08-23T10:53:47.465Z</atom:updated>
            <content:encoded><![CDATA[<p>Our socket adventure continues. Today I will talk about the packages we will use in socket communication.</p><p>Today, there are many package structures such as JSON, protobuf, msgpack are used in socket communication. Each of them has its advantages and disadvantages. You can choose any of them according to the requirements of your project or you can create your own custom package structure. Today we will create our own package structure to better understand socket communication.</p><p>First, let’s look at the journey of a message sent over the network.</p><p>Simply put, a package goes through three stages.<br>- Application Layer<br>- Operating System <br>- Network Layer (NIC)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cx3XO9LxdYKVdoMepY7wTg.jpeg" /></figure><p>For each layer there is a capacity allocated to your application. If the socket is full (e.g. the buffer is full) or empty, the operating system cannot process the data. In this case, the processing is not stopped, but the “<strong>WouldBlock”</strong> error is returned, so that the application has to try again later. This is why packet sizes are important. For example, if your application sends large packets and the other application cannot process them, then you may encounter this error.</p><p>Package management can be seen as easy. However, if we are working with large packages and need to perform fast processing, an unmanageable situation may occur. Therefore, package management is an issue that needs attention.</p><p>You may be a little confused so far. So let’s move on to our sample project. We will use our own package structure in our ‘server-time’ project that we have prepared before. This time we will send not only clock information but also memory and cpu information.</p><p>Now let’s create our package structure.</p><blockquote><em>Packet Size (2 byte) + Packet Type (1 byte) + Data</em></blockquote><p><strong>Packet Size</strong></p><p>We will be able to parse the readable data by learning the packet size and the size of the incoming data. There are two methods here. If you want, you can also include the package type and the size of the package size in the package size. Or you can only include the size of the data. I chose to add only the size of the data.</p><p><strong>Packet Type</strong></p><p>We create a binary package structure. The first byte tells us the type of the packet. We can use numbers up to 255 for this. Three packet types are enough for now.</p><p><em>1 - Time<br> 2 - Memory <br> 3 - CPU</em></p><p><strong>Data</strong></p><p>Finally, it remains to place the data we want in the package. We will calculate the size of the data as i32 (integer). Yes, I know our packet size is 2 bytes, but integer is 4–8byte value. But we have a little trick. I will explain.</p><blockquote>Bonus: Processing integer values into bytes plays a critical role in data packaging, compression, and transmission. This method is widely used in both network-based applications and low-level data processing. Please let me know if you would like a detailed usage on the subject.</blockquote><p>You can use the ‘<strong>systemstat</strong>’ package to get our system information. Now let’s write the code to create a package.</p><pre><br>async fn process(mut socket: TcpStream) {<br>  let sys = System::new();<br>  println!(&quot;Connected this client, Remote Addr: {:?}&quot;, socket.peer_addr().unwrap());<br>  socket.set_nodelay(true).unwrap();<br><br>  loop {<br>    let local = Local::now();<br>    let time = local.format(&quot;%H%M%S&quot;).to_string();<br>    let mut packet: Vec&lt;u8&gt; = vec![];<br><br>    add_packet(&amp;mut packet, 1, &amp;time); // Add time info<br><br>    if let Ok(mem) = sys.memory() {<br>      add_packet(&amp;mut packet, 2, &amp;mem.total.as_u64().to_string()); // Add memory info<br>    }<br>    if let Ok(cpu) = sys.cpu_load_aggregate() {<br>      std::thread::sleep(Duration::from_secs(1));<br>      let cpu = cpu.done().unwrap();<br>      add_packet(&amp;mut packet, 3, &amp;(cpu.user * 100.0).to_string()); // Add cpu info<br>    } else {<br>      std::thread::sleep(Duration::from_secs(1));<br>    }<br><br>    if let Err(e) = socket.write_all(&amp;packet).await { // Send it<br>      println!(&quot;During send, socket has given error: {}&quot;, e);<br>      return;<br>    }<br>  }<br>}<br><br>fn add_packet(packet: &amp;mut Vec&lt;u8&gt;, packet_type: u8, data: &amp;str) {<br>  let data = data.as_bytes();<br>  let size = data.len();<br><br>  let low = (size &amp; 0x00FF) as u8;<br>  let hi = (size &gt;&gt; 8_u8) as u8;<br><br>  packet.push(packet_type);<br>  packet.push(low);<br>  packet.push(hi);<br>  packet.extend_from_slice(&amp;data);<br>}</pre><p>When creating our package, we pay attention to the order of Type, Size and Data. As I said before, normally the size of a string value uses integer type. But we don’t want to use 4 bytes to send the size. So we use integer type as 16-bit. So we can use only 2byte space.</p><blockquote>I know, you may be a little confused at this part. I will write a different article on this subject.</blockquote><p>Yes, we create and send our package. In the next article, we will look at how to read this message on the client side. We will also talk about the definitions of ‘Little Endian and Big Endian’.</p><p>Happy coding.</p><p><a href="https://github.com/bilginerdem/server-time">bilginerdem/server-time (github.com)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdcf24658b73" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/advanced-socket-programming-with-rust-part-iv-bonus-trick-bdcf24658b73">Write from simple to advanced socket programming with Rust (Part IV)</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write from simple to advanced socket programming with Rust (Part III)]]></title>
            <link>https://medium.com/codex/write-from-simple-to-advanced-socket-programming-with-rust-part-iii-4e1204d9403e?source=rss-115a055e157a------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e1204d9403e</guid>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[connection]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[tauri]]></category>
            <category><![CDATA[socket-programming]]></category>
            <dc:creator><![CDATA[Erdem Bilgin]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 04:27:04 GMT</pubDate>
            <atom:updated>2024-08-01T09:45:56.213Z</atom:updated>
            <content:encoded><![CDATA[<p>Today, We’ll use a little bit Tauri toolkit’s. First, let’s look at Tauri’s statement on the website.</p><blockquote>Tauri is a toolkit that helps developers make applications for the major desktop platforms — using virtually any frontend framework in existence. The core is built with Rust, and the CLI leverages Node.js making Tauri a genuinely polyglot approach to creating and maintaining great apps.</blockquote><p>I think that’s enough of an explanation. I’ll try not to go into too much detail about Tauri, but we’ll need a bit of interface when we go into detail about the socket. Because, I want to create an application that we will use in the real world.</p><p><strong>watcher-app</strong></p><p>Let’s recreate our client application. I prefer to name is ‘watcher-app’. Of course, you can chosee different name.</p><p>Tauri’s ‘<em>create-tauri-app</em>’ will help you a lot.</p><pre>cargo install create-tauri-app --locked<br>cargo create-tauri-app</pre><p>Here is my configuration;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HUAqR5KSKgSBnhUssv6pig.png" /><figcaption>create-tauri-app command</figcaption></figure><p>As I said before, this article is about sockets, but I also want to briefly mention what I did with ‘Tauri’.</p><p>Firstly, I prepared the package that I will send connection information to the interface. Then I defined a HashMap to keep a list of connections. Finally, I created two tauri commands named ‘client_register’ and ‘client_delete’.</p><pre>#[derive(Clone, serde::Serialize)]<br>struct Payload {<br>  name: String,<br>  time: String,<br>  ip: String,<br>  ttl: u32,<br>}<br><br>lazy_static! {<br>  static ref CONNECTIONS: Arc&lt;Mutex&lt;HashMap&lt;String, RawFd&gt;&gt;&gt; = Arc::new(Mutex::new(HashMap::new()));<br>}<br><br>#[tauri::command]<br>fn client_register(window: Window, name: &amp;str, ip: &amp;str){}<br><br>#[tauri::command]<br>fn client_delete(window: Window, name: &amp;str){}<br><br><br>#[tokio::main]<br>async fn main() {<br>  tauri::Builder::default()<br>    .invoke_handler(tauri::generate_handler![client_register, client_delete])<br>    .run(tauri::generate_context!())<br>    .expect(&quot;error while running tauri application&quot;);<br>}</pre><p>This part was what we had to do with the tauri. Now we can move on to the socket related part.</p><p><strong>Client Register</strong></p><p>Firstly, let’s assume that we have three servers. On each of these three servers, our previously developed server-time applications are running. We will connect to each of these servers to get their time information. So we have a connection map. We will add the connections to this map with their names.</p><pre>let ip_addr = ip.to_string();<br>let name_str = name.to_string();<br><br>tauri::async_runtime::spawn(async move {<br>  let stream = TcpStream::connect(ip_addr.clone()).await.expect(&quot;Connection error&quot;);<br>  stream.set_nodelay(true).expect(&quot;Failed to set NoDelay&quot;);<br>  stream.set_linger(None).expect(&quot;Failed to set Linger&quot;);<br>  stream.set_ttl(32).expect(&quot;Faield to set TTL&quot;);<br><br>  println!(&quot;Connected!&quot;);<br><br>  let payload = Payload {<br>    name: name_str.clone(),<br>    time: &quot;00:00:00&quot;.to_string(),<br>    ip: ip_addr.clone(),<br>    ttl: 0,<br>  };<br><br>  if let Err(e) = window.emit(&quot;create&quot;, payload) {<br>    println!(&quot;Window emit (create) error: {:?}&quot;, e)<br>  };<br><br>  let raw_fd = stream.as_raw_fd();<br><br>  if let Ok(mut conns) = CONNECTIONS.lock() {<br>   conns.entry(name_str.clone()).or_insert(raw_fd.clone());<br>  }<br>});</pre><p>We register our clients and notify the interface with tauri.</p><p>There are some features that we set immediately after connecting. Let’s talk a little bit about them now.</p><p><strong>NoDelay</strong></p><p>The TCP nodelay (Nagle’s Algorithm) feature is a setting used to optimise the transmission of small data packets on TCP connections. Nagle’s algorithm allows small data packets to be accumulated and sent as a larger data packet. In this case, the data is expected to become large packets. Therefore, there may be delays in the delivery of data.</p><p>You know, the data packet we use is very small, we only send time information. Therefore, on average, there can be a delay of 200 ms per packet. To prevent this, we have turned on our NoDelay feature.</p><p><strong>Linger</strong></p><p>The Linger property controls how the connection behaves during the closing process of a TCP socket. In particular, it allows us to decide what happens to unsent data and how to manage the process of closing the socket. The linger time is specified in seconds and indicates that if the linger property is on, the socket will wait for this amount of time before closing. When close is called for the socket, the socket waits for the specified time and tries to ensure that any unsent data is sent. If all data is sent within this time, the socket closes. Otherwise, the socket closes when the time expires and the remaining data is lost.</p><p>In our example, we used the None value to turn off this feature. Thus, when we make a close request, our socket will close quickly without waiting.</p><p><strong>TTL</strong></p><p>The Time To Live (TTL) feature is used to determine the lifetime of a network packet. TTL is a value that specifies how many ‘hops’ a network packet can make as it travels through routers. The TTL value is decremented by one each time a router forwards the packet to the next network. When the TTL value reaches zero, the packet is dropped by the router and cannot reach the destination. This mechanism regulates network traffic and prevents congestion by preventing packets on the network from remaining in endless loops.</p><p>The default TTL value is 64. I preferred to set it to 32. With this information, we can find out how many routers are between us and the server. Now let’s see how we read this data.</p><pre>let mut frame = Framed::new(stream, LinesCodec::new());<br><br>while let Some(Ok(line)) = frame.next().await {<br>  let raw_socket = unsafe { std::net::TcpStream::from_raw_fd(raw_fd.clone()) };<br><br>  let payload = Payload {<br>    name: name_str.clone(),<br>    time: line,<br>    ip: ip_addr.clone(),<br>    ttl: raw_socket.ttl().unwrap(),<br>  };<br><br>  if let Err(e) = window.emit(&quot;info&quot;, payload) {<br>    println!(&quot;Window emit (time) error: {:?}&quot;, e)<br>  };<br><br>  std::mem::forget(raw_socket);<br>}</pre><p>Firstly, let’s talk about our RawFd value. Raw file descriptor (RawFd) is a low-level identifier used in Unix-based operating systems to provide access to files, sockets, or other resources. RawFd is simply an integer and is uniquely assigned by the operating system for each open file or resource. This value is also recognised by Windows as HANDLE.</p><p>I use this value both to keep it in my connection list and to read the TTL data instantaneously.</p><blockquote>This value is the identifier of the socket, so we need to specify that this value should not be removed with ‘<strong>mem::forget</strong>’.</blockquote><p>Finally, let’s look at the method for closing the connection.</p><pre>#[tauri::command]<br>fn client_delete(window: Window, name: &amp;str) {<br>  println!(&quot;Closing: {}&quot;, name);<br><br>  if let Ok(conns) = CONNECTIONS.lock() {<br>    if let Some(raw_fd) = conns.get(name) {<br>      let raw_socket = unsafe { std::net::TcpStream::from_raw_fd(*raw_fd) };<br>      raw_socket.shutdown(std::net::Shutdown::Both).unwrap();<br>      drop(raw_socket);<br><br>      let payload = Payload {<br>        name: name.to_string(),<br>        time: &quot;&quot;.to_owned(),<br>        ip: &quot;&quot;.to_owned(),<br>        ttl: 0,<br>      };<br><br>      if let Err(e) = window.emit(&quot;deleted&quot;, payload) {<br>        println!(&quot;Window emit (deleted) error: {:?}&quot;, e)<br>      };<br>    }<br>  }<br>}</pre><p>Watcher-app is ready. I shared the whole project with you on github.com.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*8dpWTjLv3tYR7WXHQtGKyQ.png" /><figcaption>watcher-app</figcaption></figure><p>In the next article, we will proceed on the server application side. On the server side, we will receive information from our other applications and create a new package format for them.</p><p><a href="https://github.com/bilginerdem/watcher-app">bilginerdem/watcher-app: Server monitor application (github.com)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e1204d9403e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/write-from-simple-to-advanced-socket-programming-with-rust-part-iii-4e1204d9403e">Write from simple to advanced socket programming with Rust (Part III)</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write from simple to advanced socket programming with Rust (Part II)]]></title>
            <link>https://medium.com/codex/write-from-simple-to-advanced-socket-programming-with-rust-part-ii-7f2d774d04cb?source=rss-115a055e157a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f2d774d04cb</guid>
            <category><![CDATA[tauri]]></category>
            <category><![CDATA[socket-programming]]></category>
            <category><![CDATA[rustpro]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Erdem Bilgin]]></dc:creator>
            <pubDate>Sat, 13 Jul 2024 17:16:53 GMT</pubDate>
            <atom:updated>2024-07-16T15:00:27.725Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello Again,</p><p>Today, we through that second part. Past part, we created a basic server socket and send to time packet to client connection. So, how to create a basic client and read time packet?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uPXEApjI4MpZsL9SvikXsw.png" /><figcaption>Server Running</figcaption></figure><p>Firstly, let’s run our server application then connect with telnet application. You see, we get time packet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*iculrrBxRQxmqq0N7d_FmA.png" /></figure><p>Now, let’s begin create a client application with RUST!</p><pre>cargo new client-time</pre><p>Then, open the ‘<strong>Cargo.toml</strong>’ file and add dependencies;</p><pre>[dependencies]<br>futures = &quot;0.3&quot;<br>tokio = { version = &quot;1.21&quot;, features = [&quot;full&quot;] }<br>tokio-util = { version = &quot;0.7&quot;, features = [&quot;codec&quot;] }</pre><p>After installing all the dependencies, I will explain the various dependencies that were not utilized in the server application.</p><p><strong>Futures</strong></p><p>It is a library used for asynchronous programming in the Rust programming language. This library has many features. I metion that the features next articles. What you need to know for now for this example is that we are using the stream feature with this library. With this feature, we process the packets coming from the server sequentially.</p><p><strong>Tokio-util</strong></p><p>This library, which is part of the Tokio ecosystem, includes various auxiliary tools that facilitate the development of asynchronous applications. We will use the codec feature in this example. With this feature, you can simply handle the encoding and decoding operations commonly used in network protocols.</p><p>Let’s write some code…</p><pre><br>#[tokio::main]<br>async fn main() {<br>    let mut addr = String::from(&quot;localhost:6379&quot;);<br>    if let Some(_) = env::args().find(|f| f.starts_with(&quot;-addr&quot;)) {<br>        addr = env::args().nth(2).expect(&quot;error input addr&quot;);<br>    } <br>    println!(&quot;Application started&quot;);<br><br>    let stream = TcpStream::connect(addr).await.expect(&quot;Connection error&quot;);<br><br>    println!(&quot;Connected!&quot;);<br>}</pre><p>Firstly, we get the address information as a parameter. We need to know where we are connected. Then we connect to the given address.</p><p>Now let’s remember our server application. The server application adds char(10) (\n) right after the time information. In this way, we will be able to see the data cleanly by splitting the incoming timestamp packets.</p><p>Here the “tokio-util” library will help us with “LineCodec”. A stream is coming from the server application. “LineCodec” will both read this stream and present the data cleanly for us.</p><pre><br>  let mut frame = Framed::new(stream, LinesCodec::new());<br><br>  while let Some(Ok(line)) = frame.next().await {<br>      println!(&quot;{}&quot;, line);<br>  }</pre><p>That’s how easy it is!</p><p>We’re getting time information now. The incoming time is accurate and clear.</p><p>I will continue to add a little more to each article. We are at the beginning of our article series. Of course, we will see more details as we progress, but we will not go into very deep details in this article series. Please try to learn network layers and how network systems work outside the series. Not only software, but also knowing how devices work will help you a lot.</p><p>In the next article, we will check the status of our servers with the interface with tauri. Stay tuned!</p><p><a href="https://github.com/bilginerdem/client-time">bilginerdem/client-time (github.com)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f2d774d04cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/write-from-simple-to-advanced-socket-programming-with-rust-part-ii-7f2d774d04cb">Write from simple to advanced socket programming with Rust (Part II)</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write from simple to advanced socket programming with Rust (Part I)]]></title>
            <link>https://medium.com/codex/write-from-simple-to-advanced-socket-programming-with-rust-part-i-cdcf243bc321?source=rss-115a055e157a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdcf243bc321</guid>
            <category><![CDATA[rust-programming-language]]></category>
            <category><![CDATA[basics]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[socket-programming]]></category>
            <dc:creator><![CDATA[Erdem Bilgin]]></dc:creator>
            <pubDate>Tue, 02 Jul 2024 13:22:34 GMT</pubDate>
            <atom:updated>2024-07-13T16:34:33.377Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m a programmer as generally work on socket programming. I had wrote socket application in many different programming language. Every language has its own challenges. As possible as I would like to share my experiences here. Today, I prefer to talk about socket programming with Rust.</p><p>I have been working on Rust for a long time. All developers that interest in Rust know that Rust is different language than others. Today, I won&#39;t talk about this differences.</p><p>I don’t want to prolong the post unnecessarily. So, I getting on topic at once.</p><figure><img alt="Send Server Time, with Dall-e" src="https://cdn-images-1.medium.com/max/1024/1*dDWeygaz3iLIbo6_y-KDjg.jpeg" /></figure><p>Basically, our program will send us the time of the computer it is running on. Sometimes, taking a time info from server as a good choose for learning application and server status. I usually prefer to use the time information for it.</p><p>Now, let’s look at the plug-ins will use;</p><ul><li>tokio.rs (1.21)</li><li>chrono (0.4)</li></ul><h4>Tokio.rs</h4><p>Tokio.rs is so popular an asynchronous runtime for the Rust programming language. Sure, you must have seen many posts on this topic on Medium. Therefore, I won’t talk about Tokio.rs. Instead, when I write code, I will put comments on the lines.</p><h4>Chrono</h4><p>Chrono is date and time library. We will take time information of server correct and fast thanks to this library.</p><p>Now, let’s create a Rust project;</p><pre>cargo new server-time</pre><p>Then, open the ‘<strong>Cargo.toml</strong>’ file and add dependencies;</p><pre>[dependencies]<br>chrono = &quot;0.4&quot;<br>tokio = { version = &quot;1.21&quot;, features = [&quot;full&quot;] }</pre><p>After all dependencies are installed we can start coding the project. We look at the what we want to the project.</p><ul><li>TCP Listening</li><li>Send to time</li></ul><pre><br>#[tokio::main]<br>async fn main() {<br>  println!(&quot;Application started&quot;);<br>}</pre><p>We should use “tokio” main macro for accessing “tokio” methods and network libraries. Then, we change to &quot;main” function as follows.</p><pre><br>#[tokio::main]<br>async fn main() {<br>  let mut port = String::from(&quot;4000&quot;);<br>  if let Some(_) = env::args().find(|f| f.starts_with(&quot;-port&quot;)) {<br>    port = env::args().nth(2).unwrap_or(String::from(&quot;4000&quot;));<br>  } <br><br>  println!(&quot;Application started&quot;);<br>  <br>  let listener = TcpListener::bind(format!(&quot;0.0.0.0:{}&quot;, port)).await.unwrap();<br><br>  println!(&quot;Waiting to clients... [Port: {}]&quot;, port);<br><br>  loop {<br>    match listener.accept().await {<br>      Ok((socket, _)) =&gt; {<br>        tokio::spawn(async move {<br>          process(socket).await;<br>        });<br>      }<br>      Err(e) =&gt; println!(&quot;Error in acception: {}&quot;, e),<br>    }<br>  }<br>}</pre><p>Let’s review codes;</p><ul><li>Fistly, we get a port number that the application will use before application starts.</li><li>Start listen to the port and waiting a clients..</li><li>Accept incoming client</li></ul><pre><br>async fn process(mut socket: TcpStream) {<br>  println!(&quot;Connected this client, Remote Addr: {:?}&quot;, socket.peer_addr().unwrap());<br>  socket.set_nodelay(true).unwrap();<br><br>  loop {<br>    std::thread::sleep(Duration::from_secs(1));<br><br>    let local = Local::now();<br>    let time = local.format(&quot;%H:%M:%S\n&quot;).to_string();<br><br>    if let Err(e) = socket.write_all(time.as_bytes()).await {<br>      println!(&quot;During send, socket has given error: {}&quot;, e);<br>      return;<br>    }<br>  }<br>}</pre><ul><li>Create a new thread for each client</li><li>Send time info to connected clients</li></ul><p>I think these are enough for the first socket example.</p><p>In the next article, we’ll get our hands dirty and write our client application. Then we’ll take a closer look at the process between the two applications.</p><p><a href="https://github.com/bilginerdem/server-time">bilginerdem/server-time (github.com)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdcf243bc321" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/write-from-simple-to-advanced-socket-programming-with-rust-part-i-cdcf243bc321">Write from simple to advanced socket programming with Rust (Part I)</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>