C# UDP 连接通信 简单示例
Udp.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets; namespace udp
{
public delegate void UdpEventHandler(object sender, UdpEventArgs e); public abstract class Udp : IUdp
{
public event UdpEventHandler Received; private int _port;
private string _ip;
public bool IsListening { get; private set; }
private Socket _sck; public Socket UdpSocket
{
get { return _sck; }
}
public string Ip
{
get { return _ip; }
set { _ip = value; }
}
public int Port
{
get { return _port; }
set
{
if (value < )
value = ;
if (value > )
value = ;
_port = value;
}
} public Udp()
{
_sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_sck.ReceiveBufferSize = UInt16.MaxValue * ;
//log
System.Diagnostics.Trace.Listeners.Clear();
System.Diagnostics.Trace.AutoFlush = true;
System.Diagnostics.Trace.Listeners.Add(new System.Diagnostics.TextWriterTraceListener("log.txt"));
} public void Listening()
{
IPAddress ip = IPAddress.Any;
try
{
if (this._ip != null)
if (!IPAddress.TryParse(this._ip, out ip))
throw new ArgumentException("IP地址错误", "Ip");
_sck.Bind(new IPEndPoint(ip, this._port)); UdpState state = new UdpState();
state.Socket = _sck;
state.Remote = new IPEndPoint(IPAddress.Any, );
_sck.BeginReceiveFrom(state.Buffer, , state.Buffer.Length, SocketFlags.None, ref state.Remote, new AsyncCallback(EndReceiveFrom), state);
IsListening = true;
}
catch (ArgumentException ex)
{
IsListening = false;
System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString() + "\t" + ex.Message);
throw ex;
}
catch (Exception ex)
{
IsListening = false;
System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString() + "\t" + ex.Message);
throw ex;
}
}
private void EndReceiveFrom(IAsyncResult ir)
{
if (IsListening)
{
UdpState state = ir.AsyncState as UdpState;
try
{
if (ir.IsCompleted)
{
int length = state.Socket.EndReceiveFrom(ir, ref state.Remote);
byte[] btReceived = new byte[length];
Buffer.BlockCopy(state.Buffer, , btReceived, , length);
OnReceived(new UdpEventArgs(btReceived, state.Remote));
}
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString() + "\t" + ex.Message+ex.Source);
}
finally
{
state.Socket.BeginReceiveFrom(state.Buffer, , state.Buffer.Length, SocketFlags.None, ref state.Remote, new AsyncCallback(EndReceiveFrom), state);
}
}
} private void OnReceived(UdpEventArgs e)
{
if (this.Received != null)
{
Received(this, e);
}
} public void Send(byte[] bt, EndPoint ep)
{
if (_sck == null) return;
try
{
this._sck.SendTo(bt, ep);
}
catch (SocketException ex)
{
System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString() + "\t" + ex.Message);
throw ex;
}
} public void Dispose()
{
if (_sck == null) return; using (_sck) ;
//this.IsListening = false;
//this._sck.Blocking = false;
//this._sck.Shutdown(SocketShutdown.Both);
//this._sck.Close();
//this._sck = null;
} }
}
IUdp.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net; namespace udp
{
public interface IUdp : IDisposable
{
event UdpEventHandler Received; void Send(byte[] bt, EndPoint ep); Socket UdpSocket { get; }
}
}
UdpEventArgs.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net; namespace udp
{
public class UdpEventArgs : EventArgs
{
private EndPoint _remote; private byte[] _rec; public byte[] Received
{
get { return _rec; }
}
public EndPoint Remote
{
get { return _remote; }
} public UdpEventArgs(byte[] data, EndPoint remote)
{
this._remote = remote;
this._rec = data;
}
}
}
UdpState.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets; namespace udp
{
internal class UdpState
{
public byte[] Buffer;
public EndPoint Remote;
public Socket Socket; public UdpState()
{
Buffer = new byte[];
}
}
}
Client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using udp;
namespace client
{
class Program
{
private const string _serverIp = "127.0.0.1";
private const int _serverPort = ; static void Main(string[] args)
{
Client client = new Client();
client.ep = new IPEndPoint(IPAddress.Parse(_serverIp), _serverPort);
client.Listening();
client.Received += new UdpEventHandler(client_Received);
while (true)
{
string tmp = Console.ReadLine();
for (int i = ; i < ; i++)
{
byte[] bt = Encoding.Default.GetBytes(tmp + i);
System.Threading.Thread t = new System.Threading.Thread(() =>
{
client.Send(bt, client.ep);
});
t.Start();
}
client.Dispose();
}
} static void client_Received(object sender, UdpEventArgs e)
{
IPEndPoint ep = e.Remote as IPEndPoint;
string tmpReceived = Encoding.Default.GetString(e.Received);
Console.WriteLine(ep.Address.ToString() + ":" + ep.Port + "--> " + tmpReceived);
}
} public class Client : Udp
{
public EndPoint ep;
public Client()
{ }
}
}
Server
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; using System.Net.Sockets;
using System.Net;
using udp; namespace server
{
class Program
{
static Server server = new Server();
static void Main(string[] args)
{
server.Port = ;
server.Listening();
if (server.IsListening)
{
server.Received += new UdpEventHandler(server_Received);
}
Console.ReadKey();
} static void server_Received(object sender, UdpEventArgs e)
{
IPEndPoint ep = e.Remote as IPEndPoint;
string tmpReceived = Encoding.Default.GetString(e.Received);
Console.WriteLine(ep.Address.ToString() + ":" + ep.Port + "--> " + tmpReceived);
///自动回复
server.Send(Encoding.Default.GetBytes("服务器已收到数据:'" + tmpReceived + "',来自:‘" + ep.Address.ToString() + ":" + ep.Port + "’"), ep);
} }
public class Server : Udp
{
private EndPoint ep;
public Server()
{
}
}
}
C# UDP 连接通信 简单示例的更多相关文章
- UDP通讯模型简单示例
1. UDP通讯模型 2. 服务器端 ① 创建一个socket,用函数socket() ② 绑定IP地址.端口等信息到socket上,用函数bind() ③ 循环接收数据,用函数recvfrom() ...
- JAVA使用jdbc连接MYSQL简单示例
以下展示的为JAVA使用jdbc连接MYSQL简单示例: import java.sql.DriverManager; import java.sql.ResultSet; import java.s ...
- redis -- python操作连接redis简单示例
1.先安装 redis,pyredis sudo pip install redis sudo pip install python-redis 2.示例: importredis >>& ...
- SQL左连接、右连接和内连接的简单示例
left join(左联接) 返回包括左表中的所有记录和右表中联结字段相等的记录: right join(右联接) 返回包括右表中的所有记录和左表中联结字段相等的记录: inner join(等值连接 ...
- 安卓中使用HttpURLConnection连接网络简单示例 --Android网络编程
MainActivity.java: package thonlon.example.cn.httpurlconnectionpro; import android.os.Bundle;import ...
- 网络编程4 网络编程之FTP上传简单示例&socketserver介绍&验证合法性连接
今日大纲: 1.FTP上传简单示例(详细代码) 2.socketserver简单示例&源码介绍 3.验证合法性连接//[秘钥加密(urandom,sendall)(注意:中文的!不能用)] 内 ...
- UDP通信简单 小结
Android手机版和电脑版 效果图: 通过WiFi局域网 电脑和手机连接通信. 电脑版本和手机版本使用了相同的消息发送头协议, 可以相互接收消息. 若有做的不好的地方还希望大家指导一下. 1. 手机 ...
- TODO:Golang UDP连接简单测试慎用Deadline
TODO:Golang UDP连接简单测试慎用Deadline UDP 是User Datagram Protocol的简称, 中文名是用户数据报协议,是OSI(Open System Interco ...
- SignalR代理对象异常:Uncaught TypeError: Cannot read property 'client' of undefined 推出的结论 SignalR 简单示例 通过三个DEMO学会SignalR的三种实现方式 SignalR推送框架两个项目永久连接通讯使用 SignalR 集线器简单实例2 用SignalR创建实时永久长连接异步网络应用程序
SignalR代理对象异常:Uncaught TypeError: Cannot read property 'client' of undefined 推出的结论 异常汇总:http://www ...
随机推荐
- 【JAVA】 @override报错的解决方法
有时候Java的Eclipse工程换一台电脑后编译总是@override报错,把@override去掉就好了,但不能从根本上解决问题,因为有时候有@override的地方超级多. 原因:这是jdk的问 ...
- 定时器的fireDate指的是触发时间
1.定时器开启后,会在经过设定的时间间隔后才会执行第一次定时操作.而不是立马开启. NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval: ...
- Maven的第一个小程序
这里是介绍关于maven的第一个小程序 关于maven的安装 : Install Maven in your computer 先看看目录结构: 这是本来的项目目录结构,由于maven有自己的目录结构 ...
- C#操作XML文档---基础
增查改删代码如下 public void CreateXML() { XmlDocument xml = new XmlDocument(); xml.AppendChild(xml.CreateXm ...
- Solr5.0配置中文分词包
Solr中默认的中文分词是用Lucene的一元分词包. 现在说明在Solr5.0中配置Lucene的SmartCN中文分词包. 1,进入Solr的安装目录,我这里是:/root/nutch/solr- ...
- webdriver中定位元素,报无法找到元素的问题
webdriver中定位元素,报无法找到元素的问题时,需要查看以下几点: 1 用火狐的firebug插件定位元素,确保这个元素的定位正确: 2 在火狐的firebug插件的,在html页签中输入fra ...
- 【java】[转]标记接口和标记注解注解
Java中的标记接口和标记注解 http://blog.sina.com.cn/s/blog_7fdce91f0101d93m.html
- Linux_安装软件包
一.软件包: 源码包 二进制包(rpm包,编译完成) 依赖性 包A-->包B-->包C 一.rpm 挂载镜像,从镜像文件中找到要安装的rpm包 [root@hadoop09-linux ~ ...
- 用JAVA写一个日历计划
效果图(自己需要在前台加css修饰)
- MUI - DIV窗体切换
神坑记录: 1.js报错异常:没有找到"innerHeight"属性? 解决方案:暂时不知原因,通过对mui.view.js进行调试得知是跳转目标页没有 .mui-navbar-l ...