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, ); // 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, , 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, ); 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!

UDP Sockets in C#的更多相关文章

  1. Windows UDP sockets: recvfrom() fails with error 10054

    https://stackoverflow.com/questions/34242622/windows-udp-sockets-recvfrom-fails-with-error-10054 #in ...

  2. 【Network】高性能 UDP 应该怎么做?

    参考资料: EPOLL-UDP-GOLANG golang udp epoll - Google 搜索 go - golang: working with multiple client/server ...

  3. 开源免费的C/C++网络库(c/c++ sockets library)

    (1)ACE 庞大.复杂,适合大型项目.开源.免费,不依赖第三方库,支持跨平台. http://www.cs.wustl.edu/~schmidt/ACE.html (2)Asio Asio基于Boo ...

  4. 开源免费的C/C++网络库(c/c++ sockets library)补充

    (1)ACE 庞大.复杂,适合大型项目.开源.免费,不依赖第三方库,支持跨平台. http://www.cs.wustl.edu/~schmidt/ACE.html (2)Asio Asio基于Boo ...

  5. 【RL-TCPnet网络教程】第17章 RL-TCPnet之UDP通信

    第17章      RL-TCPnet之UDP通信 本章节为大家讲解RL-TCPnet的UDP通信实现,学习本章节前,务必要优先学习第16章UDP用户数据报协议基础知识.有了这些基础知识之后,再搞本章 ...

  6. ss is one another utility to investigate sockets(特适合大规模tcp链接)

    原创文章,转载请注明: 转载自系统技术非业余研究 本文链接地址: ss is one another utility to investigate sockets(特适合大规模tcp链接) 具体的可以 ...

  7. 开源免费的C/C++网络库(c/c++ sockets library)(转)

    原文转自 http://blog.csdn.net/weiwangchao_/article/details/8730199 (1)ACE 庞大.复杂,适合大型项目.开源.免费,不依赖第三方库,支持跨 ...

  8. TCP/UDP server

    Simple: Sample TCP/UDP server https://msdn.microsoft.com/en-us/library/aa231754(v=vs.60).aspx Simple ...

  9. fuser - identify processes using files or sockets

    FUSER(1) User Commands FUSER(1) NAME fuser - identify processes using files or sockets SYNOPSIS fuse ...

随机推荐

  1. Netstat -tln 命令是Linux查看端口使用情况

    Netstat -tln 命令是Linux查看端口使用情况

  2. java8新特性——简介

    java8问世已经有好长时间了,但是之前项目中都没有使用到,所以一直都只是了解一些,近期刚刚换了家新公司,在开发中需要使用到java8来开发,所以也是马上赶来学习一下java8得新特性. 一.新特性 ...

  3. 【BZOJ 3090】 树形DP

    3090: Coci2009 [podjela] Description 有 N 个农民, 他们住在 N 个不同的村子里. 这 N 个村子形成一棵树.每个农民初始时获得 X 的钱.每一次操作, 一个农 ...

  4. luoguP4457 [BJOI2018]治疗之雨 概率期望 + 高斯消元

    应该是最后一道紫色的概率了....然而颜色啥也代表不了.... 首先看懂题意: 你现在有$p$点体力,你的体力上限为$n$ 在一轮中, 1.如果你的体力没有满,你有$\frac{1}{m + 1}$的 ...

  5. [BZOJ1492][NOI2007]货币兑换Cash(斜率优化+CDQ分治)

    1492: [NOI2007]货币兑换Cash Time Limit: 5 Sec  Memory Limit: 64 MBSubmit: 5838  Solved: 2345[Submit][Sta ...

  6. BZOJ 4566 JZYZOJ 1547 [haoi2016T5]找相同子串 后缀数组 并查集

    http://172.20.6.3/Problem_Show.asp?id=1547 http://www.lydsy.com/JudgeOnline/problem.php?id=4566 单纯后缀 ...

  7. SQL Server 事务复制爬坑记

    SQL Server 复制功能折腾了好几天了,现特将其配置过程以及其间遇到的问题记录下来,以备日后查阅.同时,也让“同道”同学们少走不必要的弯路.如果有不对之处,欢迎大家指正,欢迎沟通交流. 一.复制 ...

  8. java验证openssl生成的ssl证书和私钥是否匹配

    最近有一个需求上传ssl证书和私钥,但是上传之前需要验证ssl证书和私钥是否正确,其中的业务逻辑涉及到以下几点: 一.读取ssl证书,读取ssl证书公钥       要实现该功能比较简单,java里面 ...

  9. 【弱省胡策】Round #0 Flower Dance DP

    Flower Dance Time Limit: 20 Sec  Memory Limit: 256 MB 题目连接 http://162.105.80.126/contest/%E3%80%90%E ...

  10. 使用牛顿迭代法和二分法求解一个数的平方根(python语言实现)

    #牛顿迭代法 def sqrt1(x): y = 1.0 while abs(y * y - x) > 1e-6: y = (y + x/y)/2 return y #使用二分法 def sqr ...