UDP Sockets in C#

简介: UDP provides an end-to-end service different from that of TCP. In fact, UDP performs only two functions: (1) it adds another layer of addressing (po...

UDP provides an end-to-end service different from that of TCP.

In fact, UDP performs only two functions:

(1) it adds another layer of addressing (ports) to that of IP

(2) it detects data corruption that may occur in transit and discards any corrupted messages

Diffenence from TCP Sockets:

1. UDP sockets do not have to be connected before being used.

2. TCP is like telephone, and UDP is like email.

 

UDP Client

The typical UDP client goes through three steps:

1. Construct an instance of UdpClient, optionally specifying the local address and port.
2. Communicate by sending and receiving datagrams (byte arrays) using the Send() and
  Receive() methods of UdpClient.
3. When finished, deallocate the socket using the Close() method of UdpClient.

UdpEchoClient.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zeus.Thunder.Core;
using System.Net; // For IPEndPoint
using System.Net.Sockets; // For UdpClient, SocketException

namespace SharpTrainer.NetWork
{
    class UdpEchoClient : ITestCase
    {
        public void Run()
        {
            Console.Write("Input Server IP: ");
            string server = Console.ReadLine();

            Console.Write("Input Server Port: ");
            int servPort = Int32.Parse(Console.ReadLine());

            Console.Write("Input Echo String: ");
            byte[] sendPacket = Encoding.ASCII.GetBytes(Console.ReadLine());

            // Create a UdpClient instance
            UdpClient client = new UdpClient();
            try 
            {
                // Send the echo string to the specified host and port
                client.Send(sendPacket, sendPacket.Length, server, servPort);
                Console.WriteLine("Sent {0} bytes to the server...", sendPacket.Length);

                // This IPEndPoint instance will be populated with the remote sender’s
                // endpoint information after the Receive() call
                IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);

                // Attempt echo reply receive
                byte[] rcvPacket = client.Receive(ref remoteIPEndPoint);

                Console.WriteLine("Received {0} bytes from {1}: {2}", rcvPacket.Length, remoteIPEndPoint,
                    Encoding.ASCII.GetString(rcvPacket, 0, rcvPacket.Length));
            } 
            catch (SocketException se) 
            {
                Console.WriteLine(se.ErrorCode + ": " + se.Message);
            }

            client.Close();
        }
    }
}

 

UdpEchoServer.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Zeus.Thunder.Core;
using System.Net; // For IPEndPoint
using System.Net.Sockets; // For UdpClient, SocketException

namespace SharpTrainer.NetWork
{
    class UdpEchoServer : ITestCase
    {
        public void Run()
        {
            Console.Write("Input Server Port: ");
            int servPort = Int32.Parse(Console.ReadLine());

            UdpClient client = null;
             try {
                // Create an instance of UdpClient on the port to listen on
                client = new UdpClient(servPort);
            } catch (SocketException se) {
                Console.WriteLine(se.ErrorCode + ": " + se.Message);
                Environment.Exit(se.ErrorCode);
            }

            // Create an IPEndPoint instance that will be passed as a reference
            // to the Receive() call and be populated with the remote client info
            IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);

            for (;;) 
            { 
                // Run forever, receiving and echoing datagrams
                try {
                    // Receive a byte array with echo datagram packet contents
                    byte[] byteBuffer = client.Receive(ref remoteIPEndPoint);
                    Console.Write("Handling client at " + remoteIPEndPoint + " - ");
                    // Send an echo packet back to the client
                    client.Send(byteBuffer, byteBuffer.Length, remoteIPEndPoint);
                    Console.WriteLine("echoed {0} bytes.", byteBuffer.Length);
                } catch (SocketException se) {
                    Console.WriteLine(se.ErrorCode + ": " + se.Message);
                }
            }
        }
    }
}

 

运行结果:

Server端:

Handling client at 127.0.0.1:65005 - echoed 18 bytes.

 

Client端:

Input Server IP: 127.0.0.1
Input Server Port: 9999
Input Echo String: Hello Master HaKu!
Sent 18 bytes to the server...
Received 18 bytes from 127.0.0.1:9999: Hello Master HaKu!

 

目录
相关文章
|
3月前
|
网络协议 安全 网络安全
什么是TCP/UDP/HTTP?它们如何影响你的内网穿透体验?
数据的传输离不开各种协议,它们就像现实世界中的交通规则,规定了数据如何打包、寻址、传输和接收。对于使用内网穿透的用户来说,理解TCP、UDP和HTTP这些基础协议的特点,能帮助你更好地理解其性能表现,并选择最适合的配置方案。
|
5月前
|
网络协议 安全 网络安全
详细阐述 TCP、UDP、ICMPv4 和 ICMPv6 协议-以及防火墙端口原理优雅草卓伊凡
详细阐述 TCP、UDP、ICMPv4 和 ICMPv6 协议-以及防火墙端口原理优雅草卓伊凡
439 2
|
8月前
|
网络协议 Java 开发工具
全平台开源即时通讯IM框架MobileIMSDK:7端+TCP/UDP/WebSocket协议,鸿蒙NEXT端已发布,5.7K Stars
全平台开源即时通讯IM框架MobileIMSDK:7端+TCP/UDP/WebSocket协议,鸿蒙NEXT端已发布,5.7K Stars
453 1
|
12月前
|
监控 网络协议 网络性能优化
不再困惑!一文搞懂TCP与UDP的所有区别
本文介绍网络基础中TCP与UDP的区别及其应用场景。TCP是面向连接、可靠传输的协议,适用于HTTP、FTP等需要保证数据完整性的场景;UDP是无连接、不可靠但速度快的协议,适合DNS、RIP等对实时性要求高的应用。文章通过对比两者在连接方式、可靠性、速度、流量控制和数据包大小等方面的差异,帮助读者理解其各自特点与适用场景。
|
网络协议 算法 网络性能优化
|
12月前
|
存储 网络协议 安全
用于 syslog 收集的协议:TCP、UDP、RELP
系统日志是从Linux/Unix设备及网络设备生成的日志,可通过syslog服务器集中管理。日志传输支持UDP、TCP和RELP协议。UDP无连接且不可靠,不推荐使用;TCP可靠,常用于rsyslog和syslog-ng;RELP提供可靠传输和反向确认。集中管理日志有助于故障排除和安全审计,EventLog Analyzer等工具可自动收集、解析和分析日志。
725 2
|
网络协议 网络性能优化 数据处理
深入解析:TCP与UDP的核心技术差异
在网络通信的世界里,TCP(传输控制协议)和UDP(用户数据报协议)是两种核心的传输层协议,它们在确保数据传输的可靠性、效率和实时性方面扮演着不同的角色。本文将深入探讨这两种协议的技术差异,并探讨它们在不同应用场景下的适用性。
415 4
|
网络协议 前端开发 物联网
TCP和UDP区别?
本文首发于微信公众号“前端徐徐”,详细介绍了TCP和UDP两种传输层协议的核心概念、连接性和握手过程、数据传输和可靠性、延迟和效率、应用场景及头部开销。TCP面向连接、可靠、有序,适用于网页浏览、文件传输等;UDP无连接、低延迟、高效,适用于实时音视频传输、在线游戏等。
670 1
TCP和UDP区别?
|
监控 网络协议 网络性能优化
网络通信的核心选择:TCP与UDP协议深度解析
在网络通信领域,TCP(传输控制协议)和UDP(用户数据报协议)是两种基础且截然不同的传输层协议。它们各自的特点和适用场景对于网络工程师和开发者来说至关重要。本文将深入探讨TCP和UDP的核心区别,并分析它们在实际应用中的选择依据。
364 3
|
缓存 负载均衡 网络协议
面试:TCP、UDP如何解决丢包问题
TCP、UDP如何解决丢包问题。TCP:基于数据块传输/数据分片、对失序数据包重新排序以及去重、流量控制(滑动窗口)、拥塞控制、自主重传ARQ;UDP:程序执行后马上开始监听、控制报文大小、每个分割块的长度小于MTU