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!

 

目录
相关文章
|
2月前
|
存储 网络协议 算法
UDP 协议和 TCP 协议
本文介绍了UDP和TCP协议的基本结构与特性。UDP协议具有简单的报文结构,包括报头和载荷,报头由源端口、目的端口、报文长度和校验和组成。UDP使用CRC校验和来检测传输错误。相比之下,TCP协议提供更可靠的传输服务,其结构复杂,包含序列号、确认序号和标志位等字段。TCP通过确认应答和超时重传来保证数据传输的可靠性,并采用三次握手建立连接,四次挥手断开连接,确保通信的稳定性和完整性。
82 1
UDP 协议和 TCP 协议
|
3月前
|
消息中间件 网络协议 算法
UDP 和 TCP 哪个更好?
【8月更文挑战第23天】
152 0
|
3天前
|
网络协议 算法 网络性能优化
|
14天前
|
网络协议 前端开发 物联网
TCP和UDP区别?
本文首发于微信公众号“前端徐徐”,详细介绍了TCP和UDP两种传输层协议的核心概念、连接性和握手过程、数据传输和可靠性、延迟和效率、应用场景及头部开销。TCP面向连接、可靠、有序,适用于网页浏览、文件传输等;UDP无连接、低延迟、高效,适用于实时音视频传输、在线游戏等。
30 1
TCP和UDP区别?
|
6天前
|
Web App开发 缓存 网络协议
不为人知的网络编程(十八):UDP比TCP高效?还真不一定!
熟悉网络编程的(尤其搞实时音视频聊天技术的)同学们都有个约定俗成的主观论调,一提起UDP和TCP,马上想到的是UDP没有TCP可靠,但UDP肯定比TCP高效。说到UDP比TCP高效,理由是什么呢?事实真是这样吗?跟着本文咱们一探究竟!
29 10
|
16天前
|
网络协议 网络性能优化 C#
C# 一分钟浅谈:UDP 与 TCP 协议区别
【10月更文挑战第8天】在网络编程中,传输层协议的选择对应用程序的性能和可靠性至关重要。本文介绍了 TCP 和 UDP 两种常用协议的基础概念、区别及应用场景,并通过 C# 代码示例详细说明了如何处理常见的问题和易错点。TCP 适用于需要可靠传输和顺序保证的场景,而 UDP 适用于对延迟敏感且可以容忍一定数据丢失的实时应用。
24 1
|
21天前
|
网络协议 Linux 网络性能优化
Linux C/C++之TCP / UDP通信
这篇文章详细介绍了Linux下C/C++语言实现TCP和UDP通信的方法,包括网络基础、通信模型、编程示例以及TCP和UDP的优缺点比较。
29 0
Linux C/C++之TCP / UDP通信
|
24天前
|
存储 网络协议 Java
【网络】UDP和TCP之间的差别和回显服务器
【网络】UDP和TCP之间的差别和回显服务器
55 1
|
30天前
|
存储 网络协议 算法
更深层次理解传输层两协议【UDP | TCP】【UDP 缓冲区 | TCP 8种策略 | 三次握手四次挥手】
UDP和TCP各有所长,UDP以其低延迟、轻量级的特点适用于对实时性要求极高的应用,而TCP凭借其强大的错误检测、流量控制和拥塞控制机制,确保了数据的可靠传输,适用于文件传输、网页浏览等场景。理解它们的工作原理,特别是UDP的缓冲区管理和TCP的8种策略,对于优化网络应用的性能、确保数据的高效和可靠传输至关重要。开发者在选择传输层协议时,应根据实际需求权衡利弊,合理利用这两项关键技术。
49 5
|
1月前
|
网络协议 Linux 网络性能优化
Linux基础-socket详解、TCP/UDP
综上所述,Linux下的Socket编程是网络通信的重要组成部分,通过灵活运用TCP和UDP协议,开发者能够构建出满足不同需求的网络应用程序。掌握这些基础知识,是进行更复杂网络编程任务的基石。
64 1