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 (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#的更多相关文章
- Windows UDP sockets: recvfrom() fails with error 10054
https://stackoverflow.com/questions/34242622/windows-udp-sockets-recvfrom-fails-with-error-10054 #in ...
- 【Network】高性能 UDP 应该怎么做?
参考资料: EPOLL-UDP-GOLANG golang udp epoll - Google 搜索 go - golang: working with multiple client/server ...
- 开源免费的C/C++网络库(c/c++ sockets library)
(1)ACE 庞大.复杂,适合大型项目.开源.免费,不依赖第三方库,支持跨平台. http://www.cs.wustl.edu/~schmidt/ACE.html (2)Asio Asio基于Boo ...
- 开源免费的C/C++网络库(c/c++ sockets library)补充
(1)ACE 庞大.复杂,适合大型项目.开源.免费,不依赖第三方库,支持跨平台. http://www.cs.wustl.edu/~schmidt/ACE.html (2)Asio Asio基于Boo ...
- 【RL-TCPnet网络教程】第17章 RL-TCPnet之UDP通信
第17章 RL-TCPnet之UDP通信 本章节为大家讲解RL-TCPnet的UDP通信实现,学习本章节前,务必要优先学习第16章UDP用户数据报协议基础知识.有了这些基础知识之后,再搞本章 ...
- ss is one another utility to investigate sockets(特适合大规模tcp链接)
原创文章,转载请注明: 转载自系统技术非业余研究 本文链接地址: ss is one another utility to investigate sockets(特适合大规模tcp链接) 具体的可以 ...
- 开源免费的C/C++网络库(c/c++ sockets library)(转)
原文转自 http://blog.csdn.net/weiwangchao_/article/details/8730199 (1)ACE 庞大.复杂,适合大型项目.开源.免费,不依赖第三方库,支持跨 ...
- TCP/UDP server
Simple: Sample TCP/UDP server https://msdn.microsoft.com/en-us/library/aa231754(v=vs.60).aspx Simple ...
- fuser - identify processes using files or sockets
FUSER(1) User Commands FUSER(1) NAME fuser - identify processes using files or sockets SYNOPSIS fuse ...
随机推荐
- 由字符串反转(使用递归)引申出来一道Java面试题
如何面试一个从事编程工作的开发人员既困难又乏味,幸好还有很多值得参考的指南,比如:<Joel Guerilla Guide to interviewing>,但最后雇佣与否,还得由你自己决 ...
- [SDOI2014]数数 --- AC自动机 + 数位DP
[SDOI2014]数数 题目描述: 我们称一个正整数N是幸运数,当且仅当它的十进制表示中不包含数字串集合S中任意一个元素作为其子串. 例如当S=(22,333,0233)时,233是幸运数,2333 ...
- CodeForces - 1009E Intercity Travelling
题面在这里! 可以发现全是求和,直接拆开算贡献就好了 #include<bits/stdc++.h> #define ll long long using namespace std; c ...
- 【枚举】【DFS序】Gym - 101617G - Rainbow Roads
题意:一颗树,每条边有个颜色,一条路径被定义为“彩虹”,当且仅当其上没有长度大于等于2的同色子路径.一个结点被定义为“超级结点”,当且仅当从其发出的所有路径都是“彩虹”. 枚举所有长度为2,且同色的路 ...
- 2017-2018-1 JAVA实验站 冲刺 day05
2017-2018-1 JAVA实验站 冲刺 day05 各个成员今日完成的任务 小组成员 今日工作 完成进度 张韵琪 进行工作总结 100% 齐力锋 找按钮音乐 100% 张浩林 写博客 100% ...
- [CC-CHEFGRPH]Time to Study Graphs with Chef
[CC-CHEFGRPH]Time to Study Graphs with Chef 题目大意: 一个有向图可以分成\(n+2(n\le10^{12})\)层,第\(0\)层和第\(n+1\)层有\ ...
- [转]Android适配器之ArrayAdapter、SimpleAdapter和BaseAdapter的简单用法与有用代码片段
收藏ArrayAdapter.SimpleAdapter和BaseAdapter的一些简短代码片段,希望用时方便想起其用法. 1.ArrayAdapter 只可以简单的显示一行文本 代码片段: A ...
- linux基础命令学习 (八)磁盘空间
一.df linux中df命令的功能是用来检查linux服务器的文件系统的磁盘空间占用情况.于du不同的是,du是面向文件的命令,只计算被文件占用的空间.不计算文件系统metadata 占用的空间.d ...
- iOS开发经验总结——基础工程
iOS开发经验总结--依赖库 这篇博客,我想说一下开发中经常遇到的一个问题,虚拟个场景描述一下的话,应该是这样的. 项目经理:今天我们正式开始一个新项目,iOSer你负责把苹果端的APP完成,有没有问 ...
- Spring自动装配Beans
在Spring框架,可以用 auto-wiring 功能会自动装配Bean.要启用它,只需要在 <bean>定义“autowire”属性. <bean id="custom ...